When working with JSX, you will frequently need to apply CSS classes to elements. In regular HTML, you use the class attribute for this purpose.
For example:
<div class="card">
<h2>React</h2>
</div>
In JSX, you use className instead:
<div className="card">
<h2>React</h2>
</div>
className is one of the most commonly used JSX attributes because it connects your React components with CSS.
Understanding className is important because React applications rely heavily on reusable components and dynamic styling.
Why Does JSX Use className?
In HTML, the attribute is called:
class="card"
In JSX, the equivalent is:
className="card"
The reason is related to JavaScript and React’s DOM property conventions. class is a reserved keyword in JavaScript, while className is the property React uses for an element’s CSS class.
So remember:
<!-- HTML -->
<div class="card">
// JSX
<div className="card">
This is one of the first differences between HTML and JSX that React developers need to remember.
Basic className Syntax
The simplest way to use className is to provide a string.
<div className="card">
React Course
</div>
You can use it with almost any HTML element:
<h1 className="title">React</h1>
<p className="description">
Learn React from beginner to advanced.
</p>
<button className="primary-button">
Start Learning
</button>
The corresponding CSS could be:
.title {
font-size: 32px;
}
.description {
color: gray;
}
.primary-button {
padding: 10px 20px;
}
React applies these classes to the generated DOM elements.
Applying Multiple Classes
You can assign multiple CSS classes to the same element by separating their names with spaces.
<div className="card featured">
React Course
</div>
This produces:
<div class="card featured">
React Course
</div>
Both CSS classes are applied.
For example:
.card {
padding: 20px;
}
.featured {
border: 2px solid blue;
}
You can add several classes:
<div className="card featured popular large">
React Course
</div>
The value of className is still one string containing multiple class names.
Using a Variable with className
You can store the class name in a JavaScript variable.
const buttonClass = "primary-button";
<button className={buttonClass}>
Submit
</button>
Notice the curly braces:
className={buttonClass}
Because buttonClass is a JavaScript variable, JSX evaluates it.
This is different from:
className="buttonClass"
The second version uses the literal text:
buttonClass
It does not use the variable.
Static vs Dynamic className
A static class name:
<div className="card">
Content
</div>
A dynamic class name:
const className = "card";
<div className={className}>
Content
</div>
The important difference is:
className="card"
means the literal string "card".
While:
className={className}
means use the JavaScript value stored in className.
Conditional className
One of the most useful things about className is that it can change based on application data.
Suppose you have:
const isActive = true;
You can conditionally choose a class:
<div className={isActive ? "active" : "inactive"}>
Profile
</div>
If isActive is true, React uses:
active
If it is false, React uses:
inactive
This is called conditional class assignment.
Using && with Classes
You can also use the logical AND operator.
const isFeatured = true;
<div className={`card ${isFeatured && "featured"}`}>
React Course
</div>
When isFeatured is true, the resulting class string is:
card featured
However, this approach can sometimes produce unwanted values when the condition is false. For simple cases, a ternary or a carefully constructed class string may be clearer.
For example:
<div className={`card ${isFeatured ? "featured" : ""}`}>
React Course
</div>
Template Literals with className
Template literals are frequently used when multiple classes depend on JavaScript values.
const isActive = true;
const size = "large";
<div
className={`card ${isActive ? "active" : ""} ${size}`}
>
React Course
</div>
The resulting class name becomes:
card active large
This approach is useful when several parts of a class name are dynamic.
Combining Static and Dynamic Classes
You can combine a fixed class with a dynamic class.
const theme = "dark";
<div className={`card ${theme}`}>
React Course
</div>
The result is:
card dark
Another example:
const status = "success";
<div className={`message message-${status}`}>
Operation completed successfully.
</div>
The resulting class becomes:
message message-success
This allows CSS to provide different styles for different states.
Using Ternary Operators
Ternary expressions are particularly useful for two possible class states.
const isDarkMode = true;
<div className={isDarkMode ? "dark" : "light"}>
Website Content
</div>
You can also combine a base class:
<div className={`container ${isDarkMode ? "dark" : "light"}`}>
Website Content
</div>
The result is:
container dark
or:
container light
depending on the value of isDarkMode.
Multiple Conditions
Sometimes an element can have several independent states.
For example:
const isActive = true;
const isDisabled = false;
const isFeatured = true;
You could write:
<button
className={`button
${isActive ? "active" : ""}
${isDisabled ? "disabled" : ""}
${isFeatured ? "featured" : ""}
`}
>
Submit
</button>
This can work, but as the number of conditions grows, the code can become difficult to read.
For simple applications, template literals are fine. For more complex class logic, developers often use helper functions or libraries designed for conditional class names.
Creating a Helper Function
Instead of putting a large expression directly inside JSX, you can move the logic into a function.
function getButtonClass(isActive, isDisabled) {
return `button
${isActive ? "active" : ""}
${isDisabled ? "disabled" : ""}
`;
}
Then:
<button className={getButtonClass(true, false)}>
Submit
</button>
This keeps the JSX cleaner.
A more practical approach is to calculate the class before the return statement:
const buttonClass = `button ${
isActive ? "active" : ""
}`;
return (
<button className={buttonClass}>
Submit
</button>
);
className in React Components
className can also be passed to your own React components.
For example:
function Card({ className }) {
return (
<div className={className}>
Card Content
</div>
);
}
You can use it like this:
<Card className="featured-card" />
The component receives:
className
as a prop.
It then applies that value to the actual DOM element.
Combining a Component’s Default Class
Suppose a component already has a default class.
function Card({ className }) {
return (
<div className={`card ${className}`}>
Card Content
</div>
);
}
Now:
<Card className="featured" />
produces:
<div class="card featured">
Card Content
</div>
This pattern is extremely useful for reusable components.
The component provides its base styling:
card
while the parent can provide additional styling:
featured
Providing a Default Value
You can provide a default value for className.
function Card({ className = "" }) {
return (
<div className={`card ${className}`}>
Card Content
</div>
);
}
Now this works:
<Card />
without producing an undefined value.
And this also works:
<Card className="featured" />
producing:
card featured
Passing className Through Props
You can pass className through several components.
For example:
function Page() {
return <Card className="homepage-card" />;
}
Then:
function Card({ className }) {
return <CourseBox className={className} />;
}
And:
function CourseBox({ className }) {
return (
<div className={`course-box ${className}`}>
React Course
</div>
);
}
This allows a parent component to control additional styling without modifying the internal component.
className and CSS Modules
React projects can also use CSS Modules.
Suppose you have:
Button.module.css
with:
.button {
padding: 10px 20px;
}
You can import it:
import styles from "./Button.module.css";
Then use:
<button className={styles.button}>
Submit
</button>
Here, styles.button is a JavaScript value generated by the CSS Modules system.
This is different from:
className="button"
With CSS Modules, the imported class name is scoped to the component.
className with Multiple CSS Module Classes
You can combine CSS Module classes too.
<div
className={`${styles.card} ${styles.featured}`}
>
React Course
</div>
Or conditionally:
<div
className={`${styles.card} ${
isFeatured ? styles.featured : ""
}`}
>
React Course
</div>
This pattern is useful when your project uses CSS Modules.
className and Inline Styles
className and the style attribute solve different problems.
Use className when you want to apply CSS classes:
<div className="card">
React Course
</div>
Use style when you need inline JavaScript-based styles:
<div style={{ color: "blue", padding: "20px" }}>
React Course
</div>
For larger sets of reusable styles, CSS classes are often easier to maintain.
You will learn the style attribute in more detail when working with inline styles in JSX.
className with State
className becomes especially powerful when combined with React state.
For example:
import { useState } from "react";
function ToggleButton() {
const [isActive, setIsActive] = useState(false);
return (
<button
className={isActive ? "button active" : "button"}
onClick={() => setIsActive(!isActive)}
>
{isActive ? "Active" : "Inactive"}
</button>
);
}
When the button is clicked, the state changes.
React renders the component again and updates the class.
The button changes between:
button
and:
button active
This is how React can create interactive visual states.
A Practical Example
Consider a course list where available and unavailable courses have different styles.
function CourseCard({ course }) {
const cardClass = course.available
? "course-card available"
: "course-card unavailable";
return (
<article className={cardClass}>
<h2>{course.name}</h2>
<p>{course.description}</p>
<button
className={course.available ? "enroll-button" : "disabled-button"}
disabled={!course.available}
>
{course.available ? "Enroll Now" : "Unavailable"}
</button>
</article>
);
}
Example data:
const course = {
name: "React Fundamentals",
description: "Learn React from the fundamentals.",
available: true
};
Usage:
<CourseCard course={course} />
The class names are controlled by the course’s current data.
This is much more useful than hardcoding every visual state because the same component can represent different courses.
Common Mistakes
Using class
Incorrect:
<div className="card">
Content
</div>
Correct:
<div className="card">
Content
</div>
The JSX attribute should be className, not class.
Treating a Variable as a String
Incorrect:
const className = "card";
<div className="className">
Content
</div>
This applies a class literally named:
className
Correct:
<div className={className}>
Content
</div>
Forgetting Template Literal Backticks
Incorrect:
<div className="${isActive ? "active" : ""}">
Correct:
<div className={`${isActive ? "active" : ""}`}>
Putting JavaScript Expressions Directly in a String
Incorrect:
<div className="card {isActive ? 'active' : ''}">
Correct:
<div className={`card ${isActive ? "active" : ""}`}>
Creating Extremely Long Class Expressions
Avoid turning JSX into a large block of styling logic.
Instead of:
<div
className={`card ${isActive ? "active" : ""} ${
isFeatured ? "featured" : ""
} ${isDisabled ? "disabled" : ""} ${
size === "large" ? "large" : "small"
}`}
>
consider calculating the class name before the JSX:
const cardClass = `
card
${isActive ? "active" : ""}
${isFeatured ? "featured" : ""}
${isDisabled ? "disabled" : ""}
${size === "large" ? "large" : "small"}
`;
return (
<div className={cardClass}>
Content
</div>
);
For even more complex applications, a class-name utility can make this cleaner.
className Quick Reference
| Situation | Example |
|---|---|
| Single class | className="card" |
| Multiple classes | className="card featured" |
| Variable | className={cardClass} |
| Ternary | className={active ? "active" : "inactive"} |
| Template literal | className={\card ${size}`}` |
| Component prop | <Card className="featured" /> |
| CSS Module | className={styles.card} |
| Conditional CSS Module | className={isActive ? styles.active : styles.inactive} |
| State-based class | className={isOpen ? "open" : "closed"} |
Practice Exercise
Create a StatusBadge component that receives these props:
<StatusBadge
status="success"
text="Payment Completed"
/>
The component should:
- Always have the base class
status-badge. - Add
successwhen the status is"success". - Add
warningwhen the status is"warning". - Add
errorwhen the status is"error". - Display the provided
text.
For example:
<StatusBadge
status="success"
text="Payment Completed"
/>
should produce a class similar to:
status-badge success
Try implementing the conditional className yourself.
Where to Place an Image
Place this image after the section “Conditional className“.
Create a 16:9 React infographic showing how a class changes based on JavaScript state:
isActive = true
↓
className={
isActive
? "button active"
: "button"
}
↓
<button class="button active">
Use a modern developer-focused visual with React styling, JSX code, a clear conditional-flow diagram, and a dark coding-editor aesthetic.
Caption: Using dynamic and conditional className values in React
Alt text: React className changing dynamically based on a JavaScript condition
Key Takeaways
- JSX uses
classNameinstead of the HTMLclassattribute. classNameis used to apply CSS classes to JSX elements.- Multiple classes can be provided in one string separated by spaces.
- JavaScript variables can be used with
className={variable}. - Ternary expressions are useful for conditional classes.
- Template literals are useful when combining static and dynamic classes.
classNamecan be passed to custom React components as a prop.- Components can combine their default class with a class supplied by the parent.
- CSS Modules can provide class names through imported JavaScript objects.
- React state can be used to dynamically change classes.
- Complex class logic should be kept readable by moving it outside the JSX when necessary.
classNameconnects your React components with your CSS and is an essential part of building reusable interfaces.
Understanding className gives you the foundation for controlling the visual appearance and interactive states of React components.