Why Use className Instead of class in JSX in React
className instead of class because class is a reserved word in JavaScript. React uses className to set HTML classes on elements while keeping JSX valid JavaScript syntax.How It Works
Think of JSX as a mix between JavaScript and HTML. Since JSX code runs inside JavaScript, it must follow JavaScript rules. The word class is special in JavaScript because it defines classes in object-oriented programming. Using class directly in JSX would confuse the JavaScript engine.
To avoid this confusion, React uses className as a special property to assign CSS classes to HTML elements. This way, JSX stays valid JavaScript, and React knows to apply the CSS classes to the rendered HTML.
It's like having a nickname for something to avoid mix-ups. Here, className is the nickname for the HTML class attribute inside JSX.
Example
This example shows how to add a CSS class to a <div> in JSX using className. It renders a red box with text.
import React from 'react'; export default function RedBox() { return ( <div className="red-box"> This box is red because of the CSS class. </div> ); } // CSS (assume this is included in your project) // .red-box { // background-color: red; // color: white; // padding: 1rem; // border-radius: 0.5rem; // }
When to Use
Always use className in JSX when you want to add CSS classes to elements. This is necessary because JSX is JavaScript, and using class would cause errors.
For example, when styling buttons, containers, or any HTML elements in React components, use className to apply your CSS styles.
In real projects, this helps keep your code clean and error-free while allowing you to style your UI with CSS classes.
Key Points
- JSX is JavaScript: It must follow JavaScript rules, so reserved words like
classcan't be used as attribute names. - Use
className: React uses this special property to set HTML classes. - Prevents errors: Using
classin JSX causes syntax errors. - Consistent styling:
classNamelets you apply CSS classes just like in HTML.
Key Takeaways
className in JSX to assign CSS classes to elements.class is a reserved JavaScript word, so JSX uses className to avoid conflicts.className ensures your React code stays valid and styles apply correctly.class in JSX will cause syntax errors and should be avoided.