Add a CSS Class to a React Component

Recently, while working on a React project for a client in Austin, Texas, I needed to dynamically add and remove CSS classes from components based on user interaction.

At first, it looked pretty easy, just use className. But as I worked on more complex features like conditional styling and animations, I realized there were several clean and efficient ways to handle classes in React.

In this tutorial, I’ll walk you through three simple methods to add a CSS class to a React component, from static to dynamic and conditional approaches.

Method 1 – Use the className Attribute

The easiest and most common way to add a class to a React component is by using the className attribute.

In standard HTML, we use class, but in React, we use className because class is a reserved keyword in JavaScript.

Here’s a simple example:

import React from "react";
import "./App.css";

function WelcomeBanner() {
  return (
    <div className="welcome-banner">
      <h1>Welcome to React Development!</h1>
      <p>Building modern web apps is easier than ever.</p>
    </div>
  );
}

export default WelcomeBanner;

App.css

.welcome-banner {
  background-color: #0078d7;
  color: white;
  padding: 20px;
  text-align: center;
  border-radius: 8px;
}

You can see the output in the screenshot below.

Add CSS Class to a React Component

Here, I’ve applied the class welcome-banner directly using className. This is perfect when your component always needs the same styling.

Method 2 – Add a Class Conditionally

In real-world projects, we often need to apply CSS classes dynamically, for example, to highlight a button when it’s active or to show an error message.

Let’s see how we can do that using conditional rendering.

import React, { useState } from "react";
import "./App.css";

function SubscribeButton() {
  const [isSubscribed, setIsSubscribed] = useState(false);

  const handleClick = () => {
    setIsSubscribed(!isSubscribed);
  };

  return (
    <button
      className={isSubscribed ? "btn subscribed" : "btn"}
      onClick={handleClick}
    >
      {isSubscribed ? "Subscribed" : "Subscribe"}
    </button>
  );
}

export default SubscribeButton;

App.css

.btn {
  background-color: #0078d7;
  color: white;
  border: none;
  padding: 10px 18px;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
}

.subscribed {
  background-color: #28a745;
}

You can see the output in the screenshot below.

Add a CSS Class to a React Component

Here, the className changes based on the component’s state. When the user clicks the button, it toggles between btn and btn subscribed.

This is one of my favorite ways to make UI elements feel interactive and responsive.

Method 3 – Use the classnames Library

As your app grows, managing multiple conditional classes can get messy. That’s where the classnames library shines.

It lets you combine and conditionally apply multiple classes in a clean, readable way.

Step 1: Install the Library

Run this command in your terminal:

npm install classnames

Step 2: Use It in Your Component

import React, { useState } from "react";
import classNames from "classnames";
import "./App.css";

function AlertBox() {
  const [type, setType] = useState("info");

  const alertClass = classNames("alert", {
    "alert-info": type === "info",
    "alert-success": type === "success",
    "alert-error": type === "error",
  });

  return (
    <div className={alertClass}>
      <p>
        {type === "info" && "This is an info message."}
        {type === "success" && "Operation completed successfully!"}
        {type === "error" && "Something went wrong!"}
      </p>

      <div className="buttons">
        <button onClick={() => setType("info")}>Info</button>
        <button onClick={() => setType("success")}>Success</button>
        <button onClick={() => setType("error")}>Error</button>
      </div>
    </div>
  );
}

export default AlertBox;

App.css

.alert {
  padding: 15px;
  border-radius: 5px;
  margin: 10px 0;
  color: white;
  font-weight: bold;
}

.alert-info {
  background-color: #0078d7;
}

.alert-success {
  background-color: #28a745;
}

.alert-error {
  background-color: #dc3545;
}

.buttons button {
  margin-right: 10px;
  padding: 8px 12px;
  border: none;
  background-color: #f0f0f0;
  cursor: pointer;
  border-radius: 4px;
}

You can see the output in the screenshot below.

React Component Add CSS Class

The classnames library makes it easy to handle multiple conditional classes. It’s especially useful when your UI has several states or themes.

Bonus – Add Classes with Styled Components

If you’re using a modern React setup with Styled Components, you can achieve the same effect without traditional CSS files.

npm install styled-components

Then use it like this:

import React, { useState } from "react";
import styled from "styled-components";

const StyledButton = styled.button`
  background-color: ${(props) => (props.active ? "#28a745" : "#0078d7")};
  color: white;
  border: none;
  padding: 10px 18px;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
`;

function StyledToggleButton() {
  const [active, setActive] = useState(false);

  return (
    <StyledButton active={active} onClick={() => setActive(!active)}>
      {active ? "Active" : "Inactive"}
    </StyledButton>
  );
}

export default StyledToggleButton;

Styled Components let you keep your styles scoped and dynamic. You can pass props to control styling, making your code more modular and reusable.

Common Mistakes When Adding Classes in React

Here are a few mistakes I’ve seen developers make (and I’ve made them too):

  1. Using class instead of className – React will throw an error or ignore it.
  2. Forgetting to import CSS files – Always import your stylesheet at the top of the component.
  3. Overcomplicating conditional logic – Use libraries like classnames for cleaner code.
  4. Mixing inline and external styles unnecessarily – Stick to one consistent approach.

Conclusion

Adding a CSS class to a React component might seem basic, but mastering it is essential for building maintainable and dynamic interfaces.

Whether you’re working on a small business dashboard in San Francisco or a large-scale SaaS platform, these methods will help you manage styling efficiently and professionally.

You may also like to read:

Leave a Comment

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.