Search code examples
reactjsreact-state-management

Add css class onClick to idividual elements generated by mapping an array in React


<div className="sub-nav">
    <ul>
        {props.data.map((item, index) => {
            return (
                <li key={index} className="sub-nav-item" >{item.name} </li>
            );
        })}
    </ul>
</div>

Hi! I want to add an active class to an individual li when clicked, but I cannot seem to get it to work on mapped elements without adding it to all of them. This is part of a menu component in a React project. Thanks!


Solution

  • The following is hooks implementation.Incase you're using class I think you can derive from the same.

    const [selectedItemIndex,setSelectedItemIndex] = useState(null);
    
         <div className="sub-nav">
                        <ul>
                            {props.data.map((item, index) => {
                                return (
                                <li key={index} onClick={()=>setSelectedItemIndex(index)} className={`sub-nav-item ${selectedItemIndex===index?'active':''}`} >{item.name} </li>
                                );
                            })}
                        </ul>
        </div>