React

Why does React use className instead of a class attribute?

When applying CSS classes to all common DOM and SVG elements like buttons, li, a, and div in React, we use the className...

Written by Rohit Sharma · 1 min read >

When applying CSS classes to all common DOM and SVG elements like buttons, li, a, and div in React, we use the className attribute instead of the class attribute. Because of this, it alerts you each time you accidentally type class instead of className.

In fact, before React 16, if you wrote JSX containing an element that React did not understand, it would simply skip it.

Example:

<div attribute="xyz" />

In React 15, the code above would generate a div that was empty,

// React 15 output
<div />

However, with React 16, the DOM will also have this unidentified attribute “xyz”.

// React 16 output
<div attribute="xyz" />

Because of this, React 15 will just alert you and ignore the fact that you used class to specify a CSS class to any element. However, as a result of the new DOM attribute handling in React 16, it still issues a warning while also converting values to strings and passing them along.

Step 1: Use the command below to create a React application:

npx create-react-app textutils

Step 2: Once you’ve created your project folder textutils, use the following command to move there:

cd textutils

Structure of Project:

It will appear as seen below.

Example 1: To highlight this with a real-world example, let’s say we simply render a heading
 with some text inside of it using our default component App.js.

import "./App.css";
function App() {
  return <h1 class="heading">Hello, I am Rohit</h1>;
}
export default App;

Output: Because className was not used in the code above, the console displayed a warning that read: “Invalid DOM property ‘class’, Did you mean ‘className’? However, React 16 is the only version where it cautions you, therefore the output in the preceding code is unaffected.

Example 2: The warning from the previous example can be removed by substituting className, as shown in the example below.

import "./App.css";
  
function App() {
  return <h1 className="heading">Hello, I am Rohit</h1>;
}
  
export default App;

Output:

Conclusion

The only reason it uses className instead of class is because class is a reserved keyword in JavaScript and since React uses JSX, which is a JavaScript extension, we must use className rather than class attribute. The DOM property for a certain HTML attribute occasionally goes by a different name, but this is extremely rare. Class as className, for instance. However, nothing else has changed because className and class have the same semantic meaning and the className element is automatically rendered as a class attribute when JSX is rendered.
Thank you for reading my article. Hope you understand the concept the class and className attribute.

Loading

Leave a Reply

Your email address will not be published. Required fields are marked *