In React's JSX syntax, the className attribute is used instead of the traditional HTML class attribute to apply CSS styles to elements.
React uses className instead of class for historical and technical reasons:
class is a reserved keyword used to define classes. Using it in JSX could lead to ambiguity and conflicts.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>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.
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: