Web developers love React because of its many dynamic features. For example, using internal state values to specify elements’ appearance.

In this article, we’ll discuss how to conditionally add className values to JSX elements. We’ll show different ways to add a className value to elements: using ternary operator or template literals. We will also explore the classnames() utility, the best solution for adding multiple className values based on a condition, or even multiple conditions.

For example, if users enter wrong values into the input field, apply className value to highlight the error.

Setting up a condition

We can write an inline condition, like so:

<input className=`${inputValue.indexOf('@') === -1 ? "redBorder" : ""} large`></input>

In this example, we check if the value entered into the field contains ‘@’ symbol, to determine if it’s a valid e-mail and style the element accordingly.

For many reasons, it’s better to perform these checks outside of JSX. It’s better to simply reference the outcome of the condition to not have a lot of JavaScript code within JSX.

It’s better to define complex conditions and return dynamically generated className outside of JSX.

const conditionalClass = inputValue.indexOf('@') === -1 ? "redBorder" : ""
<input className=`${conditionalClass} large`></input>

You can use if, for, case and other useful syntax outside JSX. You can not do that within JSX.

These statements and keywords are often necessary for setting up a complex condition. Also, you can mix them with logical AND ( && ) and OR ( || ) operators.

Three different ways to apply a conditional className in React

The focus of this article will be to explain all three approaches to conditionally apply classes in React.

  1. classnames – An essential utility for anyone who wants to dynamically add className values to React elements. Intuitive syntax can handle even more advanced use cases, like multiple className values and even multiple conditions.
  2. Ternary operator – Most commonly used approach for setting a conditional className in React. Perfectly fine for basic purposes. May be unreadable if the condition is too complex, or if there are too many options. For example, defining which className values should apply conditionally, and which should always apply.
  3. Template literals – A cleaner, more readable way to apply conditional classes in React without installing external packages.

You should choose the approach depending on how often you want to use this feature, complexity of the condition, number of values and so on.

classnames() utility is essential to add multiple className values, or set multiple conditions. Ternary operator and template strings are fine for basic use cases, like adding one conditional className, or set a simple condition.

Set a conditional className

Let’s start with simple examples where we add one className value depending on the outcome of the condition.

Use a ternary operator to add a conditional className

JSX allows you to write JavaScript expressions directly within the structure of component layout.

Let’s look at a simplest possible example:

function App() {
  const condition = true
  const result = condition ? "large" : "small";
  return (
    <div className={result}> 
      <h1>Hello, world</h1>
    </div>
  );
}

Just a reminder, className is JSX alternative to class in HTML.

In this example, we set the value of <div> element’s className attribute to the result of a ternary operator, which returns a className value depending on the value of condition variable.

If condition variable is true, ternary operator will return 'large'. It will be the className value for <div> element. If it’s false, className value will be 'small'.

In JSX, JavaScript expressions need to be wrapped with curly braces.

Because of curly braces, React evaluates the result variable and the <div> will have a className attribute with a value of 'large'.

Use template literals to apply className conditionally

In JSX, we often set className attribute to a normal string:

<div class="large"></div>

If you replace the double quotes with backticks, you will gain the ability to embed JavaScript expressions within the string:

<div className=`${error ? "redBorder" : ""} large`></div>

In this example, the value of className attribute will be conditional. It depends on whether the error condition is evaluated as true or false.

To embed JavaScript expression in template literals, you must use the dollar symbol and curly braces, like so:

`${2+2}`

2+2 is the example of a simple JavaScript expression.

Conditionally choose between two className values in React – example

Here’s another example of a className value that is dynamically generated.

A ternary operator that evaluates the boolean value, and returns 'redBox' strings if it is true, and 'blackBox' if it’s false.

export default function App() {
  const [boolean, setBoolean] = useState(true);
  return (
    <div className={boolean ? "redBox" : "blackBox"}>
      <button onClick={() => setBoolean(!boolean)}>Change the boolean</button>
    </div>
  );
}

We initialize the boolean state variable to true, so the default className value will be 'redBox'.

clicking the button changes the className value

Open live demo and click the button that flips the current value of boolean variable.

Condition to set a className value or not – example

Sometimes you want to add a className value if the condition is satisfied, but not add any styles if the condition isn’t met.

The best and simplest way is to use JavaScript ternary operator.

export default function App() {
  return (
    <div className={2+2=4 ? "green" : null}>
    </div>
  );
}

If the condition is evaluated to true, JSX will set a conditional className with a green value. If it’s false, JSX will not have a className attribute at all.

This approach is preferable to another common pattern, to return an empty string instead of null.

It’s better because if you return an empty string, the transpiled element will still have a class attribute without any value.

a valueless class attribute

Returning null makes sure that the element will not have a valueless class attribute.

Add multiple conditional className values

As React developers, we often need to apply multiple className values. Sometimes few values are conditional, others are static (always applied). Or all of the className values are conditional.

Let’s explore how to set multiple className values based on a condition.

Add multiple conditional className values using a ternary operator – example

Sometimes you want the React element to have multiple conditional and non-conditional className values.

Here is an example where the first className value is conditional, while the other two are always applied:

export default function App() {
  const [boolean, setBoolean] = useState(true);
  return (
    <div
      className={
        (boolean ? "redBox" : "blackBox") + " " + "mainDiv" + " " + "padded"
      }
    >
      <button onClick={() => setBoolean(!boolean)}>Change the boolean</button>
    </div>
  );
}

In this case, we use the + operator to concatenate multiple strings. We conditionally apply the first className string, and concatenate two other strings, regardless of condition.

It’s also important to make sure there are spaces between strings.

The source code for this element will look something like this:

source code conditional class

As you can see, the first className is added conditionally, while the other two are always applied.

You can change the ternary operator to set multiple conditional className values. Like so:

export default function App() {
  const [boolean, setBoolean] = useState(true);
  return (
    <div
      className={
        (boolean ? "redBox flat" : "blackBox padded") + " " + "mainDiv"
      }
    >
      <button onClick={() => setBoolean(!boolean)}>Change the boolean</button>
    </div>
  );
}

Apply multiple className values using template literals – examples

Template literals allow us to use simpler syntax to apply multiple conditional classNames.

In this example, we’ll use template literals to conditionally apply one of three className values, while the other two are always applied:

export default function App() {
  const [boolean, setBoolean] = useState(true);
  return (
    <div
      className={
        `${boolean ? "redBox" : "blackBox"} mainDiv padded`
      }
    >
      <button onClick={() => setBoolean(!boolean)}>Change the boolean</button>
    </div>
  );
}

This is a much cleaner and understandable syntax. It’s also easier to leave spaces between className values instead of manually adding strings for empty space between class values.

We can add as many conditional className values as we need. For example, this is how to add multiple conditional className values:

export default function App() {
  const [boolean, setBoolean] = useState(true);
  return (
    <div
      className={
        `${boolean ? "redBox rounded" : "blackBox square"} mainDiv padded`
      }
    >
      <button onClick={() => setBoolean(!boolean)}>Change the boolean</button>
    </div>
  );
}

If the boolean state variable is true, React will add two conditional className values – ‘redBox’ and ’rounded’.

‘mainDiv’ and ‘padded’ are always applied, regardless of the condition.

Apply different sets of multiple className values in React – example

You can use template literals to conditionally apply different sets of multiple className values.

Let’s look at an example:

export default function App() {
  const [boolean, setBoolean] = useState(true);
  return (
    <div
      className={
        `${boolean ? "redBox mainDiv padded" : "blackBox secondaryDiv flat"} `
      }
    >
      <button onClick={() => setBoolean(!boolean)}>Change the boolean</button>
    </div>
  );
}

Depending on value of boolean state variable, the <div> element is going to have one of two sets of className values: ‘redBox mainDiv padded’ or ‘blackBox secondaryDiv flat’.

Let’s see how flipping the value of boolean state variable changes <div> element’s className value:

Use classnames() to conditionally set multiple className values

There’s an easy way to set complex conditions and apply className values based on the outcome of conditions.

First, install and import the classnames package.

The classnames function is pretty simple – it takes one argument – an object with key-value pairs.

import { useState } from "react";
import classNames from "classnames";
export default function App() {
  const [error] = useState(true);
  const [criticalError] = useState(false);
  return (
    <div
      className={classnames({
        padded: true,
        mainContainer: false,
        warning: error,
        dangerous: criticalError
      })}
    >
      Hello, world
    </div>
  );
}

Keys (property names) stand for all potential className values.

In the example above, the <div> element could have four className values: padded, mainContainer, warning, dangerous. However, which of these values are finally applied will depends key values.

From the example above, padded will always be applied, because it’s value is set to true.

mainContainer will never be applied, because its value is set to false.

Whether or not the warning className value is applied depends on the value of error variable. If it’s true (or truthy), then it will be applied.

Similarly, classnames() function will evaluate the value of criticalError variable to apply the ‘dangerous’ class value.

You can use AND ( && ) and OR ( || ) logical operators to chain multiple conditions.