I want to toggle active classname to particular month clicked and january should be bydefault active and these months are mapping from array
<div className="first6-months"> {Data[5].firstsixmonths.map((item, key) => ( <p className={item === "January" ? "jan" : "feb"} // onClick={(event) => handleClick(event, key)} > {item} </p> ))} </div>
CodePudding user response:
If you want to set an "active" class to the selected item that how I would do it:
const [months, setMonths] = useState('January')
const handleChange = (event) => {
setMonths(event.target.name)
}
return (
<div className="first6-months">
{Data[5].firstsixmonths.map((item, key) => (
<p className={item === month ? "active" : ""}
onClick={handleChange}
name={item}>
{item}
</p>
))}
</div>
)
CodePudding user response:
- When looping output, always put a
key
prop on your element
{Data[5].firstsixmonths.map((item, key) => ( <p key={item} onClick={() => handleClick(key)} > {item} </p> ))}
- Use some bit of state to track which month is active
const [activeItem, setActiveItem] = useState(0);
const handleClick = (key) = setActiveItem(key);
- Then set your
className
based uponactive
import classnames from `classnames`;
//...
<p className={classnames({
active: item === Data[5].firstsixmonths[activeItem]
})} onClick={() => handleClick(key)}>{item}</p>
This is the basics of what you need, but you'll probably need to play with it a little.