0

this is my code i'm trying to add a class on click to a clicked div but i have more than 1 div have the same classname so when i click to any div the toggle class added to all divs not the one which i clicked what i want to know how can i specify the div which i want to add toggle class to it

Code:

 const [isActive, setActive] = useState(false); const toggleClass = () => { setActive(!isActive) console.log('sad') } return ( <div className="command_wrapper"> <div className="command_list"> { Commands.map((item, index) => { return ( <div className="command" > <div className="command_face" onClick={toggleClass}> <h1>{item.Command}</h1> <p>{item.Description}</p> </div> <div className={isActive ? "command_body" : "disapper"}> <div className="command_usage"> <h1>Usage</h1> <p>{item.Usage}</p> </div> <div className="command_required"> <h1>Required Permissions</h1> <p>{item.premissions}</p> </div> </div> </div> ) }) } </div> </div> ``` 
1
  • You can make the separate component for Command item and put the useState logic there. Commented Feb 16, 2021 at 16:33

2 Answers 2

2

You can pass the item inside toggle function and verify if item passed is activated or just save the item clicked.

const [itemActive, setItemActive] = useState(); const toggleClass = (item) => { setItemActive(item) } return ( <div className="command_wrapper"> <div className="command_list"> { Commands.map((item, index) => { return ( <div className="command" > <div className="command_face" onClick={() => toggleClass(item)}> <h1>{item.Command}</h1> <p>{item.Description}</p> </div> <div className={item === itemActive ? "command_body" : "disapper"}> <div className="command_usage"> <h1>Usage</h1> <p>{item.Usage}</p> </div> <div className="command_required"> <h1>Required Permissions</h1> <p>{item.premissions}</p> </div> </div> </div> ) }) } </div> </div> ``` 

If item has any unique property, you can save just then, like an ID or name. I think it will be better.

Sign up to request clarification or add additional context in comments.

Comments

0
/*const [isActive, setActive] = useState(false); const toggleClass = () => { setActive(!isActive) console.log('sad') }*/ function handleClick(el){ //toggle the class which indicates selection ex. 'active' el.classList.toggle('active'); //other stuff todo } return ( <div className="command_wrapper"> <div className="command_list"> { Commands.map((item, index) => { return ( <div className="command" > //destruct event objet{event.target} <div onClick={({target})=>handleClick(target)}> <h1>{item.Command}</h1> <p>{item.Description}</p> </div> .... ... </div> ) }) } </div> </div> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.