'Updating classes on a react component
I have a functional component and my data in the storage changes, in connection with this the component is redrawn, but the classes remain from the old one
{menu.map((option: any, index: any) => (
<Text
key={index}
className={cn('menu-title', {
'menu-active': index === 0 ?? true,
})}
onClick={(e) => changeActive(option, e)}
>
{option}
</Text>
))}
through the 'menu-active', I set the active first element after redrawing, but this only works on initial page load
when the data in the mobx-store changes, the menu element is redrawn, but the class remains assigned to the old element, and the menu-active-condition does not work
Solution 1:[1]
Your code is a bit confusing as you're always assigning the "menu-active" className to the first menu item by doing 'menu-active': index === 0. Also the ?? should be used when the left-side of the operand is either null or undefined so in this case that operator is not necessary at all. And as a final note, I'd assume you should be comparing the current menu item index to a variable that contains the active item index instead of always to zero?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | André Silva |
