Categories
React Answers

How to set className with ternary operator add class ‘null’ in React?

Spread the love

Sometimes, we want to set className with ternary operator add class ‘null’ in React.

In this article, we’ll look at how to set className with ternary operator add class ‘null’ in React.

How to set className with ternary operator add class ‘null’ in React?

To set className with ternary operator add class ‘null’ in React, we can set the class name to an empty string.

For instance, we write:

import React, { useState } from "react";

export default function App() {
  const [on, setOn] = useState(false);

  return (
    <div>
      <style>
        {`.on {
          background-color: green
        }`}
      </style>
      <button onClick={() => setOn((o) => !o)}>toggle</button>
      <div className={on ? "on" : ""}>hello world</div>
    </div>
  );
}

We set className to 'on' if on is true and an empty string otherwise.

And we set the the on class to have background color green.

Therefore, when we click toggle to set on to true, we see the div having a green background color.

And if on if false, we see no background.

Conclusion

To set className with ternary operator add class ‘null’ in React, we can set the class name to an empty string.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *