How to change styles based on condition in React?

Apply conditional CSS in React using inline styles, classNames, or libraries like clsx.

beginnerConditional renderingreactconditional stylingclassNameinline styles
Published: 10/26/2025
Updated: 10/26/2025

Question

How to change styles based on condition in React?


Answer

You can conditionally apply styles in React using:

1. Inline styles:

function Status({ isOnline }) {
  return (
    <p style={{ color: isOnline ? 'green' : 'red' }}>
      {isOnline ? 'Online' : 'Offline'}
    </p>
  );
}

2. Conditional className:

function Button({ active }) {
  return (
    <button className={active ? 'btn-active' : 'btn'}>
      {active ? 'Active' : 'Inactive'}
    </button>
  );
}

Using clsx library:

npm install clsx
import clsx from 'clsx';

<button className={clsx('btn', { 'btn-active': active })}>Click Me</button>;

Real-World Example

  • Toggling theme (dark/light)
  • Showing success/error states
  • Styling active navigation links

Quick Practice

Build a button that turns green when clicked and red when unclicked.

Summary

Conditional styles in React can be applied using inline logic, className expressions, or helper libraries like clsx.

Related Videos
Watch these videos to learn more about this topic
Frequently Asked Questions

Should I use inline or class-based styles?

Use class-based for maintainability; inline is fine for quick conditions.

Can I use Tailwind for conditional classes?

Yes, use string templates or libraries like clsx.


Stay Updated

Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.