Skip to main content
illustration of random abstract shapes

React JSX className vs. class and htmlFor vs. for

Hello fellow coders! Today, we’re going to clear up a common confusion among React beginners: Why do we use className instead of class and htmlFor instead of for in JSX? Let’s dig in to understand these peculiarities of JSX.

className vs. class

In HTML, we use the class attribute to apply CSS styles to an element. But in JSX, we use className. Here’s how you would use it:

<div className="my-class">Hello, World!</div>

The reason behind this difference is that JSX is closer to JavaScript than HTML. The term class is a reserved keyword in JavaScript for class declarations, so the React team decided to use className instead to avoid any naming collisions.

Here’s what happens if you try to use class instead of className:

<div class="my-class">Hello, World!</div>

React will show a warning in the console:

Warning: Invalid DOM property `class`. Did you mean `className`?

Despite the warning, your styles will still be applied. React is smart enough to map class to className behind the scenes, but it’s best practice to stick with className.

htmlFor vs. for

The for attribute in HTML labels is replaced with htmlFor in JSX. Here’s an example:

<label htmlFor="my-input">My Input:</label>
<input id="my-input" />

The reason for this change is the same as with className and class: for is a reserved word in JavaScript, used in for-loops.

If you attempt to use for instead of htmlFor, you’ll see a similar warning as before:

Warning: Invalid DOM property `for`. Did you mean `htmlFor`?

Despite this warning, your label will still work correctly. But it’s best to stick with htmlFor to stay in line with React’s conventions and to ensure your code is easier for other React developers to understand.

In Conclusion

In React, className and htmlFor are used in place of class and for to avoid conflicts with JavaScript’s reserved keywords. It’s one of the small differences you’ll need to get used to when you’re writing JSX instead of plain HTML.

That wraps up our journey into the peculiarities of JSX for today. Here’s to writing cleaner, more understandable JSX!

As always, keep up the spirit of learning, and until next time, happy coding!

Stay in touch

Don't miss out on new posts or project updates. Hit me up on X (Twitter) for updates, queries, or some good ol' tech talk.

Follow @zkMake
Zubin Khavarian's Profile Written by Zubin Khavarian