React Tab component does not update active tab when Redux store value changes
P粉950128819
2023-08-31 17:49:11
<p>I am using Chakra UI Tab component in my React application. I have a numeric value stored in Redux and I want to change the active tab based on that value. However, when I update the numerical value in the store, the active tab does not change accordingly. How can I solve this problem? </p>
<p>Here is the code for the <code>MyTabs</code> component: </p>
<pre class="brush:php;toolbar:false;">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>
);
}</pre></p>
To ensure that the active tab in the Chakra UI Tab component is updated when the value in Redux changes, you can use the useEffect hook provided by React. The useEffect hook allows you to perform side effects such as updating the active tab when a specific dependency changes.
You can modify the MyTabs component as follows:
In this updated code, the useEffect hook is used to dispatch an operation (updateNumber) when the value changes. Make sure you have implemented the appropriate operations and reducer logic (selectNumber) in your Redux slice to handle numeric updates.
By doing this, the active tab will automatically update based on the numerical value stored in Redux.
defaultIndex
The properties are:See Controlled and Uncontrolled Components and Default Values Documentation:
You can use Controlled tab