Search code examples
reactjsdynamicreact-hooksbooleantoggle

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

  • 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