Borislav Hadzhiev
Last updated: Apr 27, 2022
Check out my new book
To toggle a class on click in React:
onClick
prop on the element.import {useState} from 'react'; import './App.css'; export default function App() { const [isActive, setIsActive] = useState(false); const handleClick = event => { // 👇️ toggle isActive state variable setIsActive(current => !current); }; return ( <div> <button className={isActive ? 'bg-salmon' : ''} onClick={handleClick}> Click </button> </div> ); }
And here is the css
for the example.
.bg-salmon { background-color: salmon; color: white; }
We initialized the state for the isActive
variable to false
in the
useState hook.
We set the onClick
prop on the button element, so every time it is clicked,
the handleClick
function is invoked.
In our handleClick
function, we simply toggle the isActive
boolean.
We used a ternary operator to conditionally add the class to the element.
<button className={isActive ? 'bg-salmon' : ''} onClick={handleClick}> Click </button>
The ternary operator is very similar to an if/else
statement.
In other words, if the isActive
variable stores a true
value, we add the
bg-salmon
class to the element, otherwise return an empty string.
Alternatively, you can use the classList.toggle()
method to toggle a class on
an element.
import './App.css'; export default function App() { const handleClick = event => { // 👇️ toggle class on click event.currentTarget.classList.toggle('bg-salmon'); }; return ( <div> <button onClick={handleClick}>Click</button> </div> ); }
We can access the element via the currentTarget
property of the event
object.
The currentTarget
property on the event
gives us access the element that the
event listener is attached to.
Whereas the target
property on the event
gives us a reference to the element
that triggered the event (could be a descendant).
The classList.toggle method removes an existing class from the element if the class is present. Otherwise, it adds the class to the element.