3
votes

i'm using material ui as the mandatory library for the current project. A page of a project requires four tabs, so I'm using the tab component from material ui library.

When I'm rendering the page which contains the tabs by default the first tab is the active tab. I want to set the fourth tab as active.

From the documentation, I see the "value" prop of the Tab. So I set the values of my four tabs to 1,2,3 and 4 for each Tab respectively. When Inavigate to the respective screen , i dispatch an action which is set property tab value in my store as 4.

Then though mapStateToProps i'm made this property accessible to my component. So the value when I enter the page is four but still the active Tab is the first one. Let me show you my code:

const mapStateToProps = state => ({
   value: state.get('tabValue');
});

const mapDispatchToProps = dispatch => ({
 tabClicked: () => setActiveTab('tabValue', 4)
})

And my component:

const Tabs = ({ value }) => (
 <Tabs>
   <Tab value={1}></Tab>
   ....
   <Tab value={value}</Tab>
 </Tabs

)

4

4 Answers

3
votes

For you to select a different tab by default use initialSelectedIndex. It will be of the form

<Tabs initialSelectedIndex={value}>
   <Tab value={1}></Tab>
   ...
  <Tab value={4}></Tab>
</Tabs>

Check https://material-ui.com/components/tabs/

1
votes

As of the latest version of material UI today (4.1) , set the default active tab through the property value defined at Tabs. Sample code below opens Tab 2 as default:

<Tabs value={1}>
        <Tab label="Tab 1"  {...a11yProps(0)} />
        <Tab  label="Tab 2" {...a11yProps(1)} />
 </Tabs>
  <TabPanel value={0} index={0}>
        Item One
  </TabPanel>
  <TabPanel value={1} index={1}>
        Item Two
  </TabPanel>
0
votes

You can use the state to set the initial tab select.

const [value, setValue] = React.useState(2);

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

https://material-ui.com/components/tabs/

-1
votes

according to MUI Tabs Doc you have to add value attr in <Tabs> for

The value of the currently selected Tab. If you don't want any selected Tab, you can set this property to false.

and according to MUI Tab Doc you have to add value attr in <Tab> for

You can provide your own value. Otherwise, we fallback to the child position index.

code example:

const Tabs = ({ value }) => (
 <Tabs value={value}>
   <Tab value={1}></Tab>
   ....
   <Tab value={value}</Tab>
 </Tabs>
)

both value in Tabs and Tab must be in the same type