3 Ways to Conditionally Apply Classes in React

Using libraries and custom solutions
Ferenc Almasi β€’ 2023 April 13 β€’ Read time 3 min read
  • twitter
  • facebook
React

When working with React components, you will often need to work with conditional classes. In this tutorial, I will show you how to approach the problem in three different ways: using libraries, custom utility functions, or inline arrays.


Using classNames

The most common way to apply class names conditionally in React is by using the classnames library. This library was created specifically for conditionally joining class names together:

Copied to clipboard! Playground
// Run `npm i classnames` in your terminal to install the package
import classNames from 'classnames'

// Using strings
<div className={classNames(
    'relative mb-4',
    !isVisible && 'hidden'
)} />

// Using arrays
<div className={classNames([
    'relative mb-4',
    !isVisible && 'hidden'
])} />

// Using objects
<div className={classNames(
    'relative mb-4',
    { hidden: !isVisible }
)} />
Using the classNames library

You can also try the clsx library, which is a smaller alternative to classnames.

When working with objects, notice that the key represents the class name, while the property is used for evaluating the condition. In the above example, a .hidden class will be applied if !isVisible evaluates to true.


Using a Custom Utility Function

If you are more concerned about the performance and the footprint of your NPM packages, you can also create the following custom utility function inside your project:

Copied to clipboard! Playground
const classNames = array => array?.filter(Boolean).join(' ')

// Using in JSX
<div className={classNames([
    'relative mb-4',
    !isVisible && 'hidden'
])} />
Using a custom utility function

This works exactly like classnames or clsx, but without an additional dependency. The only difference is that it only accepts an array and uses filter(Boolean) to filter out all falsy values, then joins it back together into a single string using join(' ').

Looking to improve your skills? Check out our interactive course to master React from start to finish.
Master Reactinfo Remove ads

Using Inline Arrays

Last but not least, for very simple solutions, we can also use a simple logical AND or ternary with an inline array in the following ways:

Copied to clipboard! Playground
<div className={[
    'relative mb-4',
    hidden && !isVisible
].join(' ')} />

// Using an outsource variable
const containerClass = ['relative mb-4', !isVisible && 'hidden'].join(' ')

// Using with ternary
const containerClass = ['relative mb-4', !isVisible ? 'hidden' : ''].join(' ')

<div className={containerClass} />
Using inline arrays for conditional classes

A ternary can also be used when different types of classes are needed depending on the condition. For example, the following code switches between two classes depending on the value of the isActive state:

Copied to clipboard!
<div className={isActive ? 'hamburger-close' : 'hamburger-open'} />

Which Solution to Use?

To help you decide on which approach you should take, you can use the following flow:

Copied to clipboard!
# Generally speaking, a library will be suitable for most situations
libary -> custom function -> inline array
  • Using libraries: Use for most cases. If you are concerned about size but still want to use a flexible third-party package, go with clsx.
  • Using custom utility functions: Use this approach if you are concerned about the JavaScript performance of your application, and you want to keep both the number of dependencies and your JavaScript code to a bare minimum.
  • Using inline arrays: Only use as a last resort for simple classes or if your codebase contains only a handful of conditional classes.
  • twitter
  • facebook
React
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.