user18036812
user18036812

Reputation:

How to close only one Div at a time in React?

Code:-

 const [Close, setClose] = useState(true)
  <div className="allDivs">
                {item.map((item, index) => {

                    // console.log("myDivs", myDivs);
                    return (
                        <Fragment key={index} >
                            <div className="tableHeaderBody" id="CLOSEDIV" style={{display: Close ? 'initial' : 'none'}}>
                                <div className="TableText">
                                    <div className="TableTextHide"></div>   <div style={{ color: "white" }} id="SHOW">{item.val}</div></div>
                                <div className="CloseIcon" id="CloseBtn"><FaCircle style={{ color: "#FC0000", width: "10px", height: "10px", alignItems: "right" }} onClick={() => setClose(false)} /></div>
                            </div>
                        </Fragment>
                    )
                })
                }

            </div>

enter image description here

I want that when i click the Red circle at any div (show in image) it close the div, but right now when i click the One div red circle its closes all the div please help.

Upvotes: 0

Views: 266

Answers (1)

Enfield Li
Enfield Li

Reputation: 2530

Try this:

Create a new component ChildComponent:

export default function ChildComponent({item}) {
  const [Close, setClose] = useState(true) // Every Child now has it's own setClose controll
  
  return (
    <Fragment>
        <div className="tableHeaderBody" id="CLOSEDIV" style={{display: Close ? 'initial' : 'none'}}>
            <div className="TableText">
                <div className="TableTextHide"></div>
                <div style={{ color: "white" }} id="SHOW">{item.val}</div>
            </div>

            <div className="CloseIcon" id="CloseBtn">
                 <FaCircle style={{ color: "#FC0000", width: "10px", height: "10px", alignItems: "right" }} onClick={() => setClose(false)} />
            </div>
        </div>
    </Fragment>
  )
}

Pass the ChildComponent to your component shown above:

<div className="allDivs">
    {item.map((item, index) => (
        <div key={index}>
            <ChildComponent item={item} />
        </div>
    ))}
</div>

Upvotes: 1

Related Questions