Why React uses className over class attribute ?
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:
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.
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: