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

Dynamic react toggle button for multiple elements

I need to toggle multiple blocks with true/false in react state, but true and false works for all blocks at the same time.

import { useState } from "react";
...
const [toggleThisElement, setToggleThisElement] = useState(false);
...

{
    data.map((d, id) => {
        return (
            <div className="single-history" key={id}>
                <div className="h-head">
                    click this div for toggle h-info block
                </div>

                <div className="h-info">toggling block</div>
            </div>
        )
    })
}

>Solution :

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

Currently, all your toggle items share the same state. To avoid that create a separate component for toggling logic called ToggleItem as below.

import { useState } from "react";

const ToggleItem = ({ discription, id }) => {
  const [toggleThisElement, setToggleThisElement] = useState(false);
  return (
    <div className="single-history" key={id}>
      <button
        className="h-head"
        onClick={() => setToggleThisElement((prev) => !prev)}
      >
        click this btn for toggle h-info block {id}
      </button>

      {toggleThisElement && <div className="h-info">{discription}</div>}
    </div>
  );
};

export default function App() {
  const data = ["first", "second", "third"];

  return (
    <>
      {data.map((d, id) => {
        return <ToggleItem id={id} discription={d} />;
      })}
    </>
  );
}

Edit nifty-snow-z4umy

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