Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Targeting one item in an Array ( React, useState)

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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'}
/>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading