Toggle a class on click in React

avatar

Borislav Hadzhiev

Last updated: Apr 27, 2022

banner

Check out my new book

Toggle a class on click in React #

To toggle a class on click in React:

  1. Set the onClick prop on the element.
  2. Store the active state in a state variable.
  3. Conditionally add the class using a ternary operator.
App.js
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.

App.css
.bg-salmon { background-color: salmon; color: white; }

toggle class on click

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.

App.js
<button className={isActive ? 'bg-salmon' : ''} onClick={handleClick}> Click </button>

The ternary operator is very similar to an if/else statement.

It checks if the value to the left of the question mark is truthy, and if it is, the operator returns the value to the left of the colon, otherwise the value to the right is returned.

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.

App.js
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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.