Search code examples
reactjsreact-tabs

Navigate between react tabs on button click


I am new to React. I am using React web tabs to create tabs in react.

How would one go about triggering a change of tab panels upon clicking a button element, I have two button, "Previous" & "Next". On click of previous button , i want to go to previous tab & On next button click it should show next tab ?

 <Tabs defaultTab="one"  vertical className="vertical-tabs" selectedIndex={this.state.selectedTabIndex} 
            onSelect={this.handleSelect}>
            <TabList>
              <Tab tabFor="one"  >BASIC INFORMATION</Tab>
              <Tab tabFor="two"  >ADVANCED INFORMATION</Tab>
              <Tab tabFor="three">ASSIGN USERS</Tab>
              <Tab tabFor="four" >TEMPLATE</Tab>
            </TabList>
            <TabPanel tabId="one">
            //BASIC INFORMATION
            </TabPanel>
            <TabPanel tabId="two">
            //ADVANCED INFORMATION
            </TabPanel>
            <TabPanel tabId="three">
            //ASSIGN USERS
            </TabPanel>
            <TabPanel tabId="four">
            //TEMPLATE
            </TabPanel>
             {
              <div>
    <Button onClick={()=>this.handlePreviousBtnChange()}>Back</Button> 
  </div>}{<div>
 <Button onClick={()=>this.handleNextBtnChange()}>Next</Button> 
</div>}                                 
</Tabs>

Please help me.Thanks in advance


Solution

  • According to this closed issue on the project, you should be able to use defaultTab to programmatically change the selected tab. https://github.com/marcuslindfeldt/react-web-tabs/issues/10#issuecomment-482846520

    Here's a short example. I made the tab ids numbers to make incrementing/decrementing easier.

    const ControllableTabs = () => {
      const [selectedTab, setSelectedTab] = useState(0);
      const tabCount = 3;
    
      return (
        <>
          <Tabs defaultTab={selectedTab.toString()}>
            <TabList>
              <Tab tabFor="0">Tab 1</Tab>
              <Tab tabFor="1">Tab 2</Tab>
              <Tab tabFor="2">Tab 3</Tab>
            </TabList>
            <TabPanel tabId="0">
              <p>Tab 1 content</p>
            </TabPanel>
            <TabPanel tabId="1">
              <p>Tab 2 content</p>
            </TabPanel>
            <TabPanel tabId="2">
              <p>Tab 3 content</p>
            </TabPanel>
          </Tabs>
          <Button onClick={() => setSelectedTab((selectedTab + tabCount - 1) % tabCount )}>Back</Button>
          <Button onClick={() => setSelectedTab((selectedTab + 1) % tabCount )}>Next</Button>
        </>
      );
    }
    

    I should note that there are other libraries that possibly suit your needs better, depending on the functionality that you desire. If you happen to be using material-ui in your project already, the Stepper component provides much more customizability. https://material-ui.com/components/steppers/#stepper