32. Why does React uses the className attribute in JSX instead of the standard HTML class attribute?
medium

In React's JSX syntax, the className attribute is used instead of the traditional HTML class attribute to apply CSS styles to elements.

Why Not Use class?

React uses className instead of class for historical and technical reasons:

  • Reserved keyword: In JavaScript, class is a reserved keyword used to define classes. Using it in JSX could lead to ambiguity and conflicts.
  • Avoiding naming conflicts: React avoids confusion between JavaScript classes and HTML classes by requiring the use of className in JSX.

Using className in JSX

Here's how you can apply a CSS class to a JSX element using className:

import React from 'react';

const Button = () => {
  return <button className="my-button">Click me!</button>;
};

This JSX code will render the following HTML in the browser:

<button class="my-button">Click me!</button>

Dynamic Class Names

You can also use dynamic values in className using template literals or utility libraries like classnames. Here's an example using template literals:

import React from 'react';

const Button = () => {
  const isDisabled = true;

  return (
    <button className={`my-button ${isDisabled ? 'disabled' : ''}`}>
      Click me!
    </button>
  );
};

This approach helps conditionally apply styles based on component state or props.


Conclusion

React uses className instead of class to avoid naming conflicts with JavaScript's reserved keywords. Understanding how className works helps you write cleaner, more effective styles in JSX components.


For styling in React, you can use:

  • className: For static or dynamic CSS classes.
  • CSS-in-JS libraries: For a more modular, component-scoped approach to styling (e.g., Styled Components, Emotion).