To all the regular DOM and SVG elements like <button>, <li>, <a>, <div>, etc. , if we want to apply the CSS classes, we use className attribute instead of class in React. That’s why it warns you every time when you mistakenly write class instead of className.
In fact, in earlier times before React 16, if you wrote JSX with an unknown element that does not recognize by React, it would simply skip it. For example:
<div myatrribute="xyz" />
The above line of code would render an empty div to the DOM in React 15,
// React 15 output <div />
But in React 16, this unknown attribute “xyz” will end up in the DOM as well.
// React 16 output <div myatrribute="xyz" />
That’s why, in React 15, when you use class to specify a css class to any element, it would just warn you and ignore that. But now due to the new DOM attributes handling in React 16, it still warns but converts values to strings and passes them through as well.
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
Example 1: Now, Let’s understand this with some practical implementation, suppose we simply render a heading <h1> with some text in its inner HTML from our default component App.js.
Javascript
import "./App.css" ; function App() { return <h1 class= "heading1" >This is an example code</h1>; } export default App; |
Output: In the above code, we have used class instead of className and hence in the console, we received a warning which says: “Invalid DOM property ‘class’, Did you mean ‘className’? ” But it only warns you in React 16, and that is why output in above code has not get affected by it.
Example 2: You can get rid of the above example’s warning by simply using the className in place of class, as done in below example:
App.js
Javascript
import "./App.css" ; function App() { return <h1 className= "heading1" >This is an example code</h1>; } export default App; |
Output:
Explanation: The only reason behind the fact that it uses className over class is that the class is a reserved keyword in JavaScript and since we use JSX in React which itself is the extension of JavaScript, so we have to use className instead of class attribute. However, there are very less few scenarios where the DOM property for a given HTML attribute uses a different name. For example class as className. But nothing has changed with it, the semantic meaning of both className and class is the same, when JSX is rendered, the className attribute is automatically rendered as a class attribute.