0

There are two tabs in my code and on click of the second tab I need to show one message but I don't know how to know when the second tab is selected.

The problem is the selectedIndex is not getting changed at all and the message which I wanted to show is not coming up.

const [selectedIndex, setSelectedIndex] = useState(0);

<Tabs selectedIndex={selectedIndex} onSelect={(index) => setSelectedIndex(index)} />

<TabList>
<Tab>One</Tab>
<Tab>Second</Tab>
</TabList>

<TabsPanel>content</TabsPanel>
<TabsPanel>content</TabsPanel>
</Tabs>

if (selectedIndex == 1) {

   //Show something

   //Need this msg outside the tabs

}

I have tried this and as per the react-tabs documentation this should work but it is actually not working in my case. Please suggest any alternative for onSelect or at least show how to change the selectedIndex while in the second tab.

James Z
  • 12,209
  • 10
  • 24
  • 44
Naidu
  • 1
  • 1

1 Answers1

0

In the documentation mentioned this method (onSelect) have three parameters, first param is current tab index, you must recieve second param (last index) to fix the problem.


[Edited] Please try this code:

    const App = () => {
  const [tabIndex, setTabIndex] = useState(0);

  return (
    <Tabs selectedIndex={tabIndex} onSelect={(index) => setTabIndex(index)}>
      <TabList>
        <Tab>Title 1</Tab>
        <Tab>Title 2</Tab>
      </TabList>
      <TabPanel>1</TabPanel>
      <TabPanel>2</TabPanel>
    </Tabs>
  );
};

<h1>{tabIndex}<h1>

if (tabIndex === 1) {

   //Show something

   //Need this msg outside the tabs

}