Last updated on May 28, 2021 by Suraj Sharma
In this tutorial, you will learn how you can add or remove classnames based on a truthy value.
There are two simple hacks to conditionally apply classnames to React components,
Using ternary operator(a?b:c),
Using a npm module called clsx
For this tutorial, I am going to create a Message
component, which has an isError
props, depending on the isError
boolean value I will add or remove .error
css class.
import React from 'react';
import './message.css';
const Message = ({ isError }) => {
return (
<p className={isError ? 'error' : 'success'}>
This is a message
</p>
);
}
export default Message;
If the isError
props is true
, .error
class gets added to the p
element otherwise, the .success
class gets added.
In another example, I'll append multiple classes inside the className attribute of p
return (
<p className={`bold-text ${isError ? 'error' : 'success'}`}>
This is a message
</p>
);
In the code above, I have used ES6 template literals to append conditional ternary operator inside the classname string.
I'm going to use clsx, a light weight library. Many open source projects like React Material UI uses it internally to conditionally apply classnames.
Let’s install clsx
,
npm install --save clsx
Now, I am going to refactor the above Message
component to use clsx
instead of ternary operator
import React from 'react';
import './message.css';
import clsx from 'clsx';
const Message = ({ isError }) => {
return (
<p className={clsx({
'success': !isError,
'error': isError
})
}
>
This is a message
</p>
);
}
export default Message;
Now, let's create a complex classname using clsx
return (
<p className={clsx('bold-text', {
'success': !isError,
'error': isError
})}>
This is a message
</p>
);
// output
// <p class="bold-text error">This is a message</p>
// or
//<p class="bold-text success">This is a message</p>
Related Solutions
How to build a React Login Form with Typescript and React hooks
How to achieve conditional routing in React using react router dom
Rate this post
Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.