add condition inside a className in reactjs

Adding Condition inside a ClassName in ReactJS

If you want to add a conditional className to a ReactJS component, there are several ways to do it. Here are some examples:

Using Ternary Operator

The easiest and most common way is to use a ternary operator. Here's an example:


  <div className={ isActive ? 'active' : 'inactive' }>
    <p>Some content here.</p>
  </div>

In the above code, the className of the div element will be "active" if isActive is true and "inactive" if it's false. You can replace isActive with any condition you want.

Using Logical AND Operator

You can also use the logical AND operator to conditionally add a className. Here's an example:


  <div className={ isSpecial && 'special' }>
    <p>Some content here.</p>
  </div>

In the above code, the className of the div element will be "special" if isSpecial is true. The className will be undefined otherwise, which means the class won't be added.

Using Template Literals

You can also use template literals to conditionally add a className. Here's an example:


  <div className={`button ${ isDisabled ? 'disabled' : '' }`}>
    <p>Some content here.</p>
  </div>

In the above code, the className of the div element will be "button disabled" if isDisabled is true. The className will be just "button" otherwise. You can replace isDisabled with any condition you want.

Using classNames Package

If you have complex conditions or want to add multiple classes, you can use the classNames package. Here's an example:


  import classNames from 'classnames';

  function Button({ isDisabled }) {
    const buttonClasses = classNames('button', { 'disabled': isDisabled });

    return (
      <div className={buttonClasses}>
        <p>Some content here.</p>
      </div>
    );
  }

In the above code, the classNames package is used to add "button" and "disabled" classes to the div element. The classes are added based on the value of isDisabled prop.

These are some of the ways you can add a conditional className to a ReactJS component. Choose the method that suits your needs and coding style.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe