Sometimes, we want to toggle class on click with React.
In this article, we’ll look at how to toggle class on click with React.
How to toggle class on click with React?
To toggle class on click with React, we can set the className prop.
For instance, we write
function MyComponent(props) {
const [isActive, setActive] = useState(false);
const toggleClass = () => {
setActive(!isActive);
};
return (
<div className={isActive ? "your-class" : null} onClick={toggleClass}>
<p>{props.text}</p>
</div>
);
}
to create the MyComponent component.
In it, we have the isActive state.
We set it with the setActive function in the toggleClass function.
In the div, we set the className prop to 'your-class' if isActive is true and null otherwise.
And we set onClick to toggleClass so toggleClass is called when we click on the button.
Conclusion
To toggle class on click with React, we can set the className prop.