How to Add or Remove a Class on click in React

avatar
Borislav Hadzhiev

Last updated: Apr 7, 2024
5 min

banner

# Table of Contents

  1. Add or Remove a Class on click in React
  2. Toggle a Class on click using event.currentTarget
  3. Combining classes conditionally on click

# Add or Remove a Class on click in React

To add or remove 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 the 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 on click setIsActive(current => !current); }; return ( <div> <button className={isActive ? 'bg-salmon' : ''} onClick={handleClick}> Click </button> </div> ); }
The code for this article is available on GitHub

And here is the CSS for the example.

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

add remove class on click

The code sample uses the useState hook to track an isActive boolean variable.

App.js
const [isActive, setIsActive] = useState(false);

If the variable is set to true, the class is added to the element, otherwise, it isn't added.

Every time the button is clicked, the handleClick function runs and toggles the state variable which causes the class to get added or removed.

App.js
const handleClick = event => { // ๐Ÿ‘‡๏ธ Toggle isActive state on click setIsActive(current => !current); };

We used the ternary operator to check if the isActive variable is set to true.

App.js
<button className={isActive ? 'bg-salmon' : ''} onClick={handleClick}> Click </button>
The code for this article is available on GitHub

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

If the expression to the left of the question mark is truthy, the operator returns the value to the left of the colon, otherwise, the value to the right of the colon is returned.

If the isActive state variable is set to true, the string bg-salmon is returned, otherwise, an empty string is returned.

You can imagine that the value before the colon is the if block and the value after the colon is the else block.

If you need to set a conditional initial value for useState, click on the following article.

Alternatively, you can programmatically add or remove a class using the event object.

# Programmatically toggle a Class on click using event.currentTarget

To toggle a class on click in React:

  1. Set the onClick prop on the element.
  2. Access the DOM element as event.currentTarget.
  3. Use the classList.toggle() method to toggle the class.
App.js
import './App.css'; export default function App() { const handleClick = event => { // ๐Ÿ‘‡๏ธ Toggle class on click event.currentTarget.classList.toggle('bg-salmon'); // ๐Ÿ‘‡๏ธ Add class on click // event.currentTarget.classList.add('bg-salmon'); // ๐Ÿ‘‡๏ธ Remove class on click // event.currentTarget.classList.remove('bg-salmon'); }; return ( <div> <button onClick={handleClick}>bobbyhadz.com</button> </div> ); }

And here is the CSS for the example.

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

react programmatically toggle class on click

The code for this article is available on GitHub
We set the onClick prop on the button element, so every time it is clicked, the handleClick function is invoked.
App.js
<button onClick={handleClick}>Click</button>

We can access the element via the currentTarget property of the event object.

App.js
const handleClick = event => { // ๐Ÿ‘‡๏ธ Toggle class on click event.currentTarget.classList.toggle('bg-salmon'); };

The currentTarget property of the event gives us access to the element that the event listener is attached to.

Whereas the target property of the event gives us a reference to the element that triggered the event (could be a descendant).

The example shows how to toggle a class using the classList.toggle method.

App.js
event.currentTarget.classList.toggle('bg-salmon');

The classList.toggle method removes an existing class from the element if the class is present. Otherwise, it adds the class to the element.

You can pass as many classes to the toggle() method as necessary.

App.js
event.currentTarget.classList.toggle( 'bg-salmon', 'my-class-2', 'my-class-3', );

If you need to add a class to the element on click, use the classList.add() method.

App.js
event.currentTarget.classList.add( 'bg-salmon', 'my-class-2', 'my-class-3', );

The classList.add() method won't add the class a second time if it's already present on the element.

If you need to remove a class from an element, use the classList.remove() method.

App.js
event.currentTarget.classList.remove( 'bg-salmon', 'my-class-2', 'my-class-3', );

The classList.remove() method ignores the class if it's not present on the element, otherwise it removes the class from the element's class list.

Note that it is generally recommended to handle updates to the DOM with conditional styles (as in the first subheading).

Directly mutating DOM nodes is not something you'll do very often in React.js, however, in this particular case, the code is quite simple and direct.

# Combining classes conditionally on click

You can use a template literal to dynamically add CSS classes to an element on click.

Template literals are delimited with backticks and allow us to embed variables and expressions using the dollar sign and curly braces ${expression} syntax.

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); }; const myClass = 'bg-salmon'; return ( <div> <div className={`text-white ${myClass}`}>Hello world</div> <br /> <button className={`font-lg ${isActive ? 'bg-salmon text-white' : ''}`} onClick={handleClick} > Click </button> </div> ); }
The code for this article is available on GitHub

And here is the CSS for the example.

App.css
.bg-salmon { background-color: salmon; } .text-white { color: white; } .font-lg { font-size: 2rem; padding: 10px 10px; }

add class dynamically

We can use a template literal to concatenate a string and a variable when setting classes.

Note that the string is enclosed in backticks ``, not in single quotes.

The dollar sign and curly braces syntax allows us to use placeholders that get evaluated.

App.js
<div className={`text-white ${myClass}`}> Hello world </div> <button className={`font-lg ${isActive ? 'bg-salmon text-white' : ''}`} onClick={handleClick} > Click </button> <div className={`text-white ${'hi'.length === 2 ? 'bg-salmon' : ''}`}> Hello world </div>
The code for this article is available on GitHub

The curly braces we wrapped the template literal in mark the beginning of an expression that has to be evaluated.

The code between the opening and closing curly brace is just JavaScript, so any variable or expression we use in our template literals will get evaluated.

The second example in the code sample uses the ternary operator.

App.js
<button className={`font-lg ${isActive ? 'bg-salmon text-white' : ''}`} onClick={handleClick} > Click </button>

If the isActive state variable is set to true, the font-lg and bg-salmon text-white classes get combined.

Otherwise, the font-lg class is returned.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev