Add Or Remove A Class On Click In React - Bobbyhadz
Maybe your like
# Table of Contents
- Add or Remove a Class on click in React
- Toggle a Class on click using event.currentTarget
- Combining classes conditionally on click
# Add or Remove a Class on click in React
To add or remove a class on click in React:
- Set the onClick prop on the element.
- Store the active state in a state variable.
- Conditionally add the class using the ternary operator.
And here is the CSS for the example.
App.cssCopied!.bg-salmon { background-color: salmon; color: white; }
The code sample uses the useState hook to track an isActive boolean variable.
App.jsCopied!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.jsCopied!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.jsCopied!<button className={isActive ? 'bg-salmon' : ''} onClick={handleClick}> Click </button> The code for this article is available on GitHubThe 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.
Want to learn more about working with classes in React? Check out these resources: Find all Elements by className in React,Check if an Element contains a class in React,Get the Class name of an element in React.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:
- Set the onClick prop on the element.
- Access the DOM element as event.currentTarget.
- Use the classList.toggle() method to toggle the class.
And here is the CSS for the example.
App.cssCopied!.bg-salmon { background-color: salmon; color: white; }
We can access the element via the currentTarget property of the event object.
App.jsCopied!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.jsCopied!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.jsCopied!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.jsCopied!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.jsCopied!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.jsCopied!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 GitHubAnd here is the CSS for the example.
App.cssCopied!.bg-salmon { background-color: salmon; } .text-white { color: white; } .font-lg { font-size: 2rem; padding: 10px 10px; }
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.jsCopied!<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 GitHubThe 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.jsCopied!<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:
- Get the Class name of an element in React
- Find all Elements by className in React
- Check if an Element contains a class in React
- Add a Class or Styles to the Body element in React
Tag » Add Classname To Jsx Element
-
How To Dynamically Add A Class To Manual Class Names?
-
How To Add Class Name In Jsx In React Js Code Example
-
How To Dynamically Add CSS Classes To React Elements Using State »
-
Dynamically Apply ClassName Values In React - Delft Stack
-
Styles Et CSS - React
-
Éléments DOM - React
-
How To Add Classes Dynamically Based On State Or Props In React
-
assName - Référence Web API | MDN
-
How To Assign A Class To An Element - Pluralsight
-
How To Add A Class Name - W3Schools
-
React/ReactJS: Add Class Conditionally - SCRIPTVERSE
-
How To Add Multiple Class Names In React - Reactgo
-
Why React Uses ClassName Over Class Attribute ? - GeeksforGeeks
-
Elements & JSX | React - ReScript