How to Conditionally Apply Class Attributes in ReactJS

Conditionally applying class attributes in ReactJS can be done using various methods. Here’s a detailed guide on how to achieve this using different approaches.

1. Using JavaScript Ternary Operator

The simplest method is to use the JavaScript ternary operator directly within the className attribute.

import React, { useState } from 'react';

const ConditionalClassComponent = () => {
  const [isActive, setIsActive] = useState(false);

  return (
    <div>
      <button onClick={() => setIsActive(!isActive)}>
        Toggle Active State
      </button>
      <div className={isActive ? 'active' : 'inactive'}>
        This div's class changes based on the state.
      </div>
    </div>
  );
};

export default ConditionalClassComponent;

2. Using Template Literals

You can also use template literals to conditionally add classes.

import React, { useState } from 'react';

const ConditionalClassComponent = () => {
  const [isActive, setIsActive] = useState(false);

  return (
    <div>
      <button onClick={() => setIsActive(!isActive)}>
        Toggle Active State
      </button>
      <div className={`base-class ${isActive ? 'active' : ''}`}>
        This div's class changes based on the state.
      </div>
    </div>
  );
};

export default ConditionalClassComponent;

3. Using class names Library

The class names library is a popular choice for conditionally applying class names.

Step 1. Install classnames.

npm install classnames

Step 2. Use class names in Your Component.

import React, { useState } from 'react';
import classNames from 'classnames';

const ConditionalClassComponent = () => {
  const [isActive, setIsActive] = useState(false);

  const divClass = classNames({
    'base-class': true,
    'active': isActive,
    'inactive': !isActive
  });

  return (
    <div>
      <button onClick={() => setIsActive(!isActive)}>
        Toggle Active State
      </button>
      <div className={divClass}>
        This div's class changes based on the state.
      </div>
    </div>
  );
};

export default ConditionalClassComponent;

4. Using Conditional Rendering with && Operator

You can conditionally concatenate class names using the logical && operator.

import React, { useState } from 'react';

const ConditionalClassComponent = () => {
  const [isActive, setIsActive] = useState(false);

  return (
    <div>
      <button onClick={() => setIsActive(!isActive)}>
        Toggle Active State
      </button>
      <div className={`base-class ${isActive && 'active'}`}>
        This div's class changes based on the state.
      </div>
    </div>
  );
};

export default ConditionalClassComponent;

5. Using Array.join() Method

Another approach is to use an array to build class names and join them with spaces.

import React, { useState } from 'react';

const ConditionalClassComponent = () => {
  const [isActive, setIsActive] = useState(false);

  const classes = ['base-class'];
  if (isActive) classes.push('active');
  else classes.push('inactive');

  return (
    <div>
      <button onClick={() => setIsActive(!isActive)}>
        Toggle Active State
      </button>
      <div className={classes.join(' ')}>
        This div's class changes based on the state.
      </div>
    </div>
  );
};

export default ConditionalClassComponent;

6. Using Object Spread Syntax

You can use the object spread syntax to dynamically build the className string.

import React, { useState } from 'react';

const ConditionalClassComponent = () => {
  const [isActive, setIsActive] = useState(false);

  const baseClass = 'base-class';
  const activeClass = isActive ? 'active' : 'inactive';

  return (
    <div>
      <button onClick={() => setIsActive(!isActive)}>
        Toggle Active State
      </button>
      <div className={`${baseClass} ${activeClass}`}>
        This div's class changes based on the state.
      </div>
    </div>
  );
};

export default ConditionalClassComponent;

Summary

Each method has its use cases and advantages. The class names library is particularly useful when you need to handle complex conditional logic. Using template literals and ternary operators is great for simpler conditions. Choose the method that best fits the complexity of your class name conditions.