简体   繁体   中英

Set a tab as active in material ui tab component

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

)

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/

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>

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/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM