Conditional ClassNames

2022-04-20

One of the most common ways to control element styles in React is to apply style classes based on some condition. For example you might need to apply a class named "active" to a open a menu or provide visual feedback on a button.

Here are two methods for implementing conditional ClassNames on a <button/> element in React.

Using a Ternary Operator

This is the simplest method because it does not require adding an npm package.

Here is a React component which has an active prop and returns a <button/> element with the class theButton:

import React from 'react';
const Button = ({ active }) => {
return <button className='theButton' />;
};
export default Button;

Now here it is using a ternary statement to add the class active when the prop active is true:

import React from 'react';
const Button = ({ active }) => {
return <button className={`theButton ${active ? 'active' : ''}`} />;
};
export default Button;

The ternary statement is placed inside of a template literal and wrapped with ${} so it returns either active or "" when evaluated. This method could be used to add any number of classes to an element, the following example adds a disabled class based on a disabled prop.

import React from 'react';
const Button = ({ disabled }) => {
return (
<button
className={`theButton ${active ? 'active' : ''} ${
disabled ? 'disabled' : ''
}`}
/>
);
};
export default Button;

Using the classnames library

classnames is an npm package which makes writing conditional classes in React more concise.

Here is the last example re-written using the classnames library:

import React from 'react';
import cx from 'classnames';
const Button = ({ disabled }) => {
return (
<button
className={cx('theButton', { active: active, disabled: disabled })}
/>
);
};
export default Button;