How to Conditionally Set className Values in React

Irakli Tchigladze Feb 02, 2024
  1. Set the className Conditionally in React
  2. Use the Ternary Operator to Set the className Conditionally in React
  3. Use the classNames Package to Set the className Conditionally in React
  4. Use the clsx() Function to Set the className Conditionally in React
How to Conditionally Set className Values in React

When online customers were happy to have a single destination to shop online, the days are long gone. These days, internet users have countless options for spending time online, and their expectations for customer experience are rising.

Businesses are under increasing pressure to develop user-friendly websites, which might look simple, but require a lot of work to develop and maintain.

Set the className Conditionally in React

React is a popular JavaScript-based framework for developing website UI. It uses the template language JSX, like HTML but has dynamic features.

One of the biggest advantages of JSX is that it allows you to apply attributes conditionally. Classes are set using the className attribute (class is a reserved word in React).

Inline styles can be set using the styles attribute.

Conditionally setting the className attribute can be useful in many ways. For instance, you could implement a switch element that allows users to toggle between the dark and light modes.

Conditions that determine the final value of the className attribute depend on the values from either state or props objects. The state is used to maintain and update variables based on user inputs, such as a text field or the value of a checkbox button.

The Props object holds data passed down from a parent to the child component. Changing either props and className values triggers a re-render of the entire component, executing the comparison and updating the className property value.

Without further ado, let’s look at how to apply styles conditionally.

Use the Ternary Operator to Set the className Conditionally in React

JSX allows you to set attributes equal to valid JavaScript expressions that return a certain value. For instance, className="dark" would always set the className to 'dark'.

Instead, you can set the value of the className attribute to a JavaScript expression, which evaluates certain variables to determine the value of the className attribute. Let’s take a look at the example.

export default function App() {
  const [dark, setDark] = useState(false);
  return (
    <div className={dark ? "dark" : ""}>
      <input type="checkbox" onChange={() => setDark(!dark)}></input>
      Switch to The Opposite
    </div>
  );
}

You can try out the live demo yourself.

In this case, we use double curly braces to set the className attribute equal to a ternary operator, which determines the final className value depending on the value of the dark state variable. If it is true, JavaScript will apply the 'dark' string as the value; if not, it will apply nothing.

We could also instruct it to apply any X string if the dark state variable is true and any Y string if it is false.

You could also have a mix of className strings that should always apply and those that should be applied conditionally. Let’s take a look.

export default function App() {
  const [dark, setDark] = useState(false);
  return (
    <div className={`large ${dark ? "dark" : ""}`}>
      <input type="checkbox" onChange={() => setDark(!dark)}></input>
      Switch to The Opposite
    </div>
  );
}

In this case, the className attribute will have a value of 'large' no matter what, and it will also apply className 'dark' if the state variable is true.

Template literals (``) are the latest feature of JavaScript ES6. Since React is based on JavaScript, you can also use them in React apps.

Use the classNames Package to Set the className Conditionally in React

The JavaScript community developed a classNames package to easily set conditions to apply values to the className attribute conditionally. To install it, enter the following command in your CLI.

npm install classnames

Then you can do the following.

export default function App() {
  const [dark, setDark] = useState(false);
  return (
    <div className={classNames({"large": true, "nightMode": dark})}>
      <input type="checkbox" onChange={() => setDark(!dark)}></input>
      Switch to The Opposite
    </div>
  );
}

We have one object argument to the classNames() function, where the key-value pairs represent the className values and the conditions for applying them.

The 'large' value will always be applied in the above example since its value is set to true. The 'nightMode' will only be applied to the className attribute if the state variable dark evaluates to true.

Use the clsx() Function to Set the className Conditionally in React

Since JavaScript developers often need to apply classes conditionally, they also developed the clsx() function to address this problem.

The clsx() function can be used in many ways. Let’s explore how our application would look if we set the className attribute using the clsx() function.

export default function App() {
  const [dark, setDark] = useState(false);
  return (
    <div className={clsx({"large": true, "nightMode": dark})}>
      <input type="checkbox" onChange={() => setDark(!dark)}></input>
      Switch to The Opposite
    </div>
  );
}

To learn more about the function, what it returns, and how it works, check out the official npm page.

Irakli Tchigladze avatar Irakli Tchigladze avatar

Irakli is a writer who loves computers and helping people solve their technical problems. He lives in Georgia and enjoys spending time with animals.

LinkedIn