George Welder George Welder - 20 days ago 8
React JSX Question

Simulate Material-UI Tabbar Click programmatically / with Shortcut

I am using material UIs tabs in my electron/ react application like so:

<Tabs>
<Tab label="View1" >
<View1 />
</Tab>
<Tab
label="View2">
<View2 />
</Tab>
<Tab label="View3" >
<View3 />
</Tab>
<Tab label="View4" >
<View4 />
</Tab>
</Tabs>


I now want to press a shortcut, and in doing so, change the view. So, for example, say Tab1 is active and View1 is rendered. I then press
Cmd + 2
and then Tab2 will opened (with View2 being active), in exactly the same way as if I had clicked on Tab2. How would I do this? I have tried a few things, and I would have an idea how to do this without material UI, but I am confused by the material UI syntax.

Answer Source

You can send 1 prop to Tabs to control what tab opens:

    <Tabs value={this.state.tabIndex}>
      <Tab label="View1" >
        <View1 />
      </Tab>
      <Tab
        label="View2">
        <View2 />
      </Tab>
      <Tab label="View3" >
        <View3 />
      </Tab>
      <Tab label="View4" >
        <View4 />
      </Tab>
    </Tabs> 

Then add a method to change its value:

changeTab = (tabIndex) => {
  this.setState({ tabIndex })
}