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
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>
className instead to avoid any naming collisions.
Here’s what happens if you try to use
class instead of
<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
className behind the scenes, but it’s best practice to stick with
htmlFor vs. for
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
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.
htmlFor are used in place of
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