Search code examples
javascriptreactjsreduxreact-reduxchakra-ui

React Tab component not updating active tab when Redux store value changes


I am using the Chakra UI Tab component in my React application. I have a number value stored in Redux, and I want to change the active tab based on this value. However, when I update the number value in the store, the active tab does not change accordingly. How can I fix this issue?

Here is the code for MyTabs component:

function MyTabs() {
  const number = useSelector(selectnumber);

  console.log(number);

  return (
    <Tabs defaultIndex={number}>
      <TabPanels>
        <TabPanel>
          <Image boxSize="200px" fit="cover" src="" />
        </TabPanel>
        <TabPanel>
          <Image boxSize="200px" fit="cover" src="" />
        </TabPanel>
      </TabPanels>
      <TabList>
        <Tab>Naruto</Tab>
        <Tab>Sasuke</Tab>
      </TabList>
    </Tabs>
  );
}

Solution

  • The defaultIndex prop is:

    The initial index of the selected tab (in uncontrolled mode)

    See Controlled and uncontrolled components and Default Values doc:

    In the React rendering lifecycle, the value attribute on form elements will override the value in the DOM. With an uncontrolled component, you often want React to specify the initial value, but leave subsequent updates uncontrolled. To handle this case, you can specify a defaultValue attribute instead of value. Changing the value of defaultValue attribute after a component has mounted will not cause any update of the value in the DOM.

    You can use Controlled Tabs

    const tabIndex = useSelector(selectnumber);
    const dispatch = useDispatch();
    
    <Tabs 
      index={tabIndex} 
      onChange={(index) => dispatch({ type: 'SET_TAB_INDEX', payload: { index } })}>
    </Tabs>