0
0
ReactConceptBeginner · 3 min read

Why Use className Instead of class in JSX in React

In JSX, you use 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.

jsx
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;
// }
Output
A red rectangular box with white text saying: "This box is red because of the CSS class."
🎯

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 class can't be used as attribute names.
  • Use className: React uses this special property to set HTML classes.
  • Prevents errors: Using class in JSX causes syntax errors.
  • Consistent styling: className lets you apply CSS classes just like in HTML.

Key Takeaways

Always use 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.
Using class in JSX will cause syntax errors and should be avoided.