How to Add Class in JSX: Simple React Class Usage
In JSX, use the
className attribute to add CSS classes to elements instead of class. For example, <div className="my-class"></div> applies the CSS class my-class to the div.Syntax
In JSX, you add CSS classes using the className attribute because class is a reserved word in JavaScript. The value is a string with one or more class names separated by spaces.
className: The attribute to set CSS classes in JSX.- String value: One or more class names as a string.
jsx
<div className="example-class">Content here</div>Output
A div element with the CSS class 'example-class' applied.
Example
This example shows a React functional component that adds a CSS class to a <button> element using className. The button will have the styles defined for the class btn-primary.
jsx
import React from 'react'; function MyButton() { return <button className="btn-primary">Click me</button>; } export default MyButton;
Output
A button labeled 'Click me' styled with the 'btn-primary' CSS class.
Common Pitfalls
Many beginners try to use class instead of className in JSX, which causes errors or warnings because class is a reserved JavaScript word. Also, forgetting to use quotes around the class names or passing non-string values can cause issues.
jsx
/* Wrong way - causes error or warning */ <div className="wrong-class">Wrong usage</div> /* Right way */ <div className="correct-class">Correct usage</div>
Output
The first div will cause an error or warning; the second div renders correctly with the CSS class.
Quick Reference
| Attribute | Usage | Notes |
|---|---|---|
| className | Used to add CSS classes in JSX | Must be a string with class names |
| class | Not used in JSX | Reserved word in JavaScript, causes errors |
| className={variable} | Add classes dynamically | Variable must be a string |
Key Takeaways
Always use
className instead of class in JSX to add CSS classes.The value of
className must be a string with one or more class names separated by spaces.Using
class in JSX causes errors because it is a reserved JavaScript word.You can dynamically set classes by passing a string variable to
className.Remember to use quotes around class names when writing JSX.