Thanks to visit codestin.com
Credit goes to coreui.io

How to apply conditional class names in React

Applying different CSS classes based on component state or props is essential for creating dynamic and interactive user interfaces in React applications. As the creator of CoreUI, a widely used open-source UI library, and with over 25 years of experience in software development, I’ve implemented countless components that require conditional styling based on user interactions and data states. The most effective approach is using template literals with conditional logic, which provides clean, readable code for simple conditions. For complex conditional class logic, the classnames library offers superior maintainability and readability.

Use template literals with conditional operators to apply classes based on component state or props.

function Button({ isActive, isPrimary }) {
  const className = `btn ${isActive ? 'active' : ''} ${isPrimary ? 'btn-primary' : 'btn-secondary'}`

  return <button className={className}>Click me</button>
}

Template literals allow you to dynamically construct className strings using conditional operators. The ternary operator condition ? 'class-if-true' : 'class-if-false' is perfect for binary conditions, while logical AND condition && 'class' works well when you only need to add a class conditionally. For complex conditions, consider using the classnames library: className={classNames('btn', { active: isActive, 'btn-primary': isPrimary })}.

Best Practice Note:

This is the exact approach we use in CoreUI React components for handling button states, form validation classes, and responsive utilities. The classnames library becomes invaluable when managing multiple conditional classes with complex logic.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
What is globalThis in JavaScript?
What is globalThis in JavaScript?

How to loop through a 2D array in JavaScript
How to loop through a 2D array in JavaScript

Passing props to child components in React function components
Passing props to child components in React function components

How to check if an array is empty in JavaScript?
How to check if an array is empty in JavaScript?

Answers by CoreUI Core Team