I am new to react. I created an array of items with each switch element, the problem is: when I click on one item all items are activated at once!
const dashboardItems = ["news", "notifications", "letters"];
const Settings = (props) => {
const { t } = useTranslation("settings");
const [isActive, setIsActive] = useState(false);
const handleClick = () => {
setIsActive(!isActive);
};
return (
<SideMenu class="dashboard-settings">
<SideMenu.Item>
<SideMenu.Header>{t("Dashboard Settings")}</SideMenu.Header>
</SideMenu.Item>
{dashboardItems.map((dashboardItem) => (
<SideMenu.Item key={dashboardItem}>
{t(dashboardItem)}{" "}
<Switch
onClick={handleClick}
status={isActive ? "active" : "inactive"}
/>
</SideMenu.Item>
))}
</SideMenu>
);
};
I tried many solutions I found through search but they did not work.
>Solution :
You’re using a single value for all items. Instead convert the isActive state to an object (like the example), or array (use indexes instead of item), and toggle the item on the object.
The state:
const [isActive, setIsActive] = useState({});
The switch:
<Switch
onClick={() => {
setIsActive(s => ({
...s,
[dashboardItem]: !s[dashboardItem]
}))
}
status={isActive[dashboardItem] ? 'active' : 'inactive'}
/>