How to Toggle Classes in ReactJS

Shraddha Paghdar Feb 15, 2024
How to Toggle Classes in ReactJS

Today, we will use a code example to learn how to toggle classes in ReactJS.

Toggle Classes in ReactJS

React uses the Virtual DOM idea to update the DOM elements. You can modify an element’s class property using conditional statements, rendering the class following the user’s selections.

The conditional (ternary) operator is the only one in JavaScript that accepts three operands. This operator is typically used to replace an if...else expression.

The three operands are:

  1. A necessary condition is followed by a question mark (?).
  2. An expression is to be executed if the condition is true followed by a colon (:).
  3. This expression will be executed if the condition is false.

Syntax:

condition ? expressionIfTrue : expressionIfFalse

The use of conditional statements inside functional components is demonstrated by the example below. The class components can utilize a similar strategy.

const [className, setClassName] = useState('blue')
return (
    <Fragment><p className = {className ? className : 'blue'}>Hello world!
    </p>
      <button onClick={() => setClassName(null)}>Change to Default</button>
    <button onClick = {() => setClassName('red')}>Change to Red<
        /button>
      <button onClick={() => setClassName('yellow')}>Change to Yellow</button>
    <button onClick = {() => setClassName('green')}>Change to
        Green</button>
    </Fragment>)

In the above example, we defined the className variable. When the user updates it to Red, the value is set to Red, and when the user updates it to Default, the class Red is removed.

If className is provided, we will use that class; otherwise, we will use blue as the default class. It is useful when you have numerous classes and want the default class to be used if none are present.

Run the above code in Replit (here is the demo), which is compatible with React.js. It will display the following outcome:

Output:

toggle classes in reactjs - output

Shraddha Paghdar avatar Shraddha Paghdar avatar

Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.

LinkedIn

Related Article - React Class