How to Dynamically Add CSS Classes to React Elements Using State
Last Updated: 10 October 2021
Introduction
Here's how to add classes dynamically to elements in React.
Example - Using States
import React, { useState } from "react"
const [hidden, setHidden] = useState(true)
const toggleHidden = () => {
setHidden(!hidden)
}
render() {
return (
<div>
<button onClick={toggleHidden}>TOGGLE HIDDEN</button>
<div className={`toggle-div ${hidden ? "hidden" : ""}`}>
<h1>I'm inside the hidden div</h1>
</div>
</div>
);
}
NOTE: There are a couple different ways to set the classes.
- With JSX expression
className={"toggle-div" + (hidden ? " hidden" : "")}
- With template literals:
className={`toggle-div ${hidden ? "hidden" : ""}`}