How to know which react tab we are on

191 views Asked by At

There are two tabs in my code and on click of the second tab I need to show one message but I'm not knowing 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(1);

<Tabs selectedIndex={selectedIndex} onSelect={(index) => setSelectedIndex(index)} />
<TabList>
<Tab>One</Tab>
<Tab>Second</Tab>
</TabList>
<TabsPanel>content</TabsPanel>
<TabsPanel>content</TabsPanel>
</Tabs>

if (selectedIndex == 2) {
   //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 atleast show how to change the selectedIndex while in the second tab.

1

There are 1 answers

7
0stone0 On

Seems like you're trying to use Controlled mode, which is activated by passing the selectedIndex prop.

Your issue is caused by setting the default state to 1 where as the first tab has index 0. So change the useState to:

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

Then you can show the current tab as:

{'Current tab index: ' + (selectedIndex + 1)}

When using Uncontrolled mode, you don't need an onSelect.

The Library will render the needed tab when using the following structure:

const Component = (
    <Tabs>
        <TabList>
            <Tab>One</Tab>
            <Tab>Second</Tab>
        </TabList>

        <TabPanel>
            <p>
                CONTENT - TAB - ONE
            </p>
        </TabPanel>
        <TabPanel>
            <p>
                CONTENT - TAB - SECOND
            </p>
        </TabPanel>
    </Tabs>
);