reactjs / react-tabs

An accessible and easy tab component for ReactJS.
https://reactcommunity.org/react-tabs/
MIT License
3.1k stars 447 forks source link

Bug with using index as the active tab where removing a tab can change the selected tab. #434

Closed AdnanTheExcellent closed 2 years ago

AdnanTheExcellent commented 2 years ago

I'm coming across an issue where if i have a selected tab (lets say index = 4) and i remove tab at index = 2, my current selected tab changes on me. since index = 4 would now be at 3 after the removal of tab 2.

Heres an example of this happening on the avengers example:

image

I am currently selected as iron man which is index = 4. if i uncheck captain america (at index = 2) then thor becomes the selected tab

image

The root cause of this is using an array index as the selected tab. React recommends that indexes shouldn't be used as keys for lists so that situations like this don't happen.

https://reactjs.org/docs/lists-and-keys.html

image

It would be great if we can assign a key for each tab and have the selected tab be based of the key instead of an index in controlled mode. That would fix this bug.

danez commented 2 years ago

Thanks for reporting.

I just checked and fixed the example to behave correctly (https://github.com/reactjs/react-tabs/commit/ca34e7506fe37bd49345e9cedcb238e7d219e1da)

What I do in the example is set the correct keys (https://github.com/reactjs/react-tabs/blob/main/examples/src/components/examples/Avengers.js#L76). Internally react-tabs does not set any keys.

The important part is to update the selectedIndex when elements are added or removed.