Hackforge Academy

Category: react

Conditional styling in React

Published on 06 May 2026

Explanation

Conditional styling in React means applying different CSS styles based on conditions like state, props, user actions, or data values. It is useful for active buttons, error messages, dark mode, validation, loading states, and dynamic UI updates.

Code:

function App() {
  const isActive = true;

  return (
    <button className={
isActive ? 'activeBtn' : 'inactiveBtn'}>
      Click Me
    </button>
  );
}

Explanation

You can apply inline conditional styles directly using the style attribute. This is useful for dynamic colors, visibility, spacing, and animations.

Code:

function App() {
  const isError = true;

  return (
    <h1 style={{ 
color: isError ? 'red' : 'green' }}>
      Status Message
    </h1>
  );
}

Explanation

Conditional styling with multiple classes can be done using template literals. This is commonly used in cards, forms, and navigation menus.

Code:

function App() {
  const isDark = true;

  return (
    <div className={
`card ${isDark ? 'dark' : 'light'}`}>
      Theme Card
    </div>
  );
}

Explanation

Conditional styling is often used with state changes in React. Example: changing button color when clicked.

Code:

import { useState } from 'react';

function App() {
  const [liked, setLiked] = useState(false);

  return (
    <button
      className={liked ? 
'likedBtn' : 'normalBtn'}
      onClick={() => setLiked(!liked)}
    >
      {liked ? 'Liked' : 'Like'}
    </button>
  );
}

Explanation

In Tailwind CSS with React, conditional styling is done using dynamic class names. This is widely used in modern React projects.

Code:

function App() {
  const isActive = true;

  return (
    <button
      className={isActive ? 
'bg-blue-500 text-white p-2' :
 'bg-gray-300 p-2'}
    >
      Tailwind Button
    </button>
  );
}

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community