Conditionally Add Multiple Classnames in React & Next.js

Surjith S M

Surjith S M

· 2 min read

Have you even had a problem with joining class names & dynamic or conditional props variables together in a React or Next.js project? In this article, I will show you two methods you can use right now. Let's start with a bad example.

How to add multiple classes to a ReactJS Component?

Here's a regular(bad) implementation of multiple classnames with props. The main use case is when we have to render conditional classnames. We can use template literal strings and && operator.

// Not the best way

export default function Container(props) {
return ( <div className={`container mx-auto ${props.className && props.className}`}> {props.children} </div> ); }

What's wrong with this approach?

If there are props.classNames, it will render as we expected. But if the props are empty, this is what react will output.

<div class="container mx-auto false">
content </div>

Look at the false property. This is something we have to avoid.

Method 1: Conditionally apply CSS Classes in React & Next.js

Here's a better implementation to conditionally applying class attributes in react without false values.

export default function Container(props) {
  return (
<div className={`container mx-auto ${props.className ? props.className : ""}`}>
{props.children} </div> ); }

This time we changed the && to a ternary ? : operation to add multiple classes with ternary if statement in React or Preact.

Method 2: Conditional classnames in React & Next.js using Simple Utility Function

But there is a better way. Create the following function in your utils section. This is a 2 line alternative to the famous classnames npm package. You may mimic the functionality without using this npm plugin.

export const cx = (...classNames) =>
  classNames.filter(Boolean).join(" ");

Now, you can use this function like this:

import { cx } from "@utils/all";

export default function Container(props) {
  return (
    <div className={cx("container mx-auto", props.className)}>
      {props.children}
    </div>
  );
}

Pretty neat right?

Of course the classnames npm package provides more robust testcases if you might have an edge cases. But for a simple project, its an overkill and you can use this function as an alternative.

Subscribe to our newsletter for more tips like this.

Subscribe to Newsletter

Provide your email to get email notification when we launch new products or publish new articles