How to conditionally apply class names in React JS

#react #clsx

Last updated on Aug 27, 2020 by Suraj Sharma



In this tutorial, you will learn how you can add class names based on a truthy condition or remove class names when the condition is false.

There are a couple of approaches to conditionally join class names in react. One is using a ternary operator and the another one is using external libraries like classnames, clsx and etc.



Getting started


For this tutorial, I am going to create a Message component, which has one props called ‘error, depending upon the boolean value of error, error class or success class will get added.


Using a ternary operator


import React from 'react';
import './message.css';

const Message = ({error}) => {
  return (
    <p className={error ? 'error' : 'success'}>
      This is a message
    </p>
  );
}

export default Message;

This is a simple example of conditionally applying css classes to an element in react.

If the error props is true .error class gets applied to the p element, else the .success class gets applied.

Now, you will learn how you can conditionally append a class name to an element.


return (
  <p className={`bold-text ${error ? 'error' : 'success'}`}>
    This is a message
  </p>
);

I have used ES6 template literals to append a ternary operator inside a string.



Using a 3rd party library


For this tutorial, we are going to use clsx, very light weight and many open source libraries, for instance, React Material UI uses it internally to conditionally apply class names.

Let’s install it using


npm install --save clsx

Now, I am going to refactor the above Message component to use clsx instead of ternary operator


return (
    <p className={clsx({
     'success': !error,
     'error': error
    })}>
      This is a message
    </p>
  );

Now, let's append a class name using clsx


return (
  <p className={clsx('bold-text',{
    'success': !error,
    'error': error
  })}>
    This is a message
  </p>
);


Conclusion


I would suggest using a ternary operator to conditionally apply classes to your react components because using a third party library for a simple task like can badly affect your application's performance.

But if your project has a requirement, which you think requires an external library like clsx for conditionally applying classes, then use it.



Related Articles




Suraj Sharma is a JavaScript Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.