How to add a class to HTML in JSX?

How to use JSX in React.js? »

Adding a class to an HTML element in JSX is quite simple. Let’s take an example. Suppose you want to add a class named “greeting” to a paragraph <p> element.

In normal HTML, you’d do:

<p class="greeting">
 Some paragraph here 
</p>

In JSX:

<p className="greeting">
 Some paragraph 
</p>

You probably noticed that class was replaced by className. But why’s that?

From ES6 onwards, we have a class keyword in Javascript. ES developers didn’t want to conflict between the Javascript class and the JSX class. However, there’s a community in ES who believe that when you use the class keyword inside JSX, it should be understandable that it is the JSX class and not the ES/Javascript class. ES should be smart enough to understand that part. Therefore, in the newer versions of React, you can, in fact use class instead of className in JSX as well. However, these versions will still support className keyword. Just to be on the safe side, I’d recommend using className only when writing JSX.

Note: It is worth notifying that when you want to use a “for” attribute inside a “label” element in JSX, you must use “htmlFor” instead. This is for the same reason as discussed above. You don’t want React to get confused between javascript for loop and HTML label for.

Leave a Comment