Skip to content Skip to sidebar Skip to footer

React How To Toggle A Button That Is Used In Multiple Parts?

I have an icon that I toggle to close a tab setCloseTabToggle(!closeTabToggle)} /> its state: const [closeTabToggle, setCloseTab

Solution 1:

Instead of storing a single boolean in closeTabToggle, you could instead store an array of booleans.

const [toggleArray, setToggleArray] = useState([false, false, false]);

Each of the boolean values can correspond to each of your clickable icons. If all your icons are the same components, you could map over the toggleArray and render an icon for each item.

{toggleArray.map((item, i) => (
        <imgkey={i}src={upArrow}alt=""onClick={() => {
          handleIconClick(i);
        }} />
      ))}

handleIconClick would look like this:

consthandleIconClick = (i) => {
    const temp = [...toggleArray];
    temp[i] = !temp[i];
    setToggleArray(temp);
  };

So clicking an icon will change the corresponding boolean with the same index in the toggleArray.

Finally, to change the classNames for your Form.Group elements.

<Form.Group className={toggleArray[0] ? `closed-tab-true` : ''}/>
<Form.Group className={toggleArray[1] ? `closed-tab-true` : ''}/>
<Form.Group className={toggleArray[2] ? `closed-tab-true` : ''}/>

Solution 2:

The simplest way if want to handle multiple tabs with different image

const [tab, setTab] = useState(1)

Set the unique id for each tab

<imgsrc={upArrow}alt=""onClick={()=>setTab(1)} />
<imgsrc={upArrow}alt=""onClick={()=>setTab(2)} />
<imgsrc={upArrow}alt=""onClick={()=>setTab(3)} />

then hide and show based on your css

<Form.GroupclassName={tab===1 ? `d-block` : 'd-none'}>One</Form.Group><Form.GroupclassName={tab===2 ? `d-block` : 'd-none'}>two</Form.Group><Form.GroupclassName={tab===3 ? `d-block` : 'd-none'}>three</Form.Group>

Post a Comment for "React How To Toggle A Button That Is Used In Multiple Parts?"