Set a tab as active in material ui tab component

11,284

Solution 1

For you to select a different tab by default use initialSelectedIndex.

For older versions of material ui, it will be of the form

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

For newer versions >4

<Tabs value={value}>
  <Tab label="Tab1" />
  <Tab label="Tab2" />
  <Tab label="Tab3" />
</Tabs>

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

Solution 2

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>
Share:
11,284
user7334203
Author by

user7334203

Updated on June 04, 2022

Comments

  • user7334203
    user7334203 almost 2 years

    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
    

    )

  • Fogus
    Fogus over 3 years
    This property doesn't exist in the current version material-ui.com/api/tabs (even the link is changed)
  • cdoshi
    cdoshi over 2 years
    Fixed the answer @Fogus