Set the `for` attribute on a Label element in React


Borislav Hadzhiev

Last updated: Apr 23, 2022


Photo from Unsplash

Set the for attribute on a Label element in React #

To set the for attribute on a Label element in React, use the htmlFor prop on the element, e.g. <label htmlFor="firstName">First Name</label>. The htmlFor prop is used because for is a reserved word in JavaScript.

export default function App() { return ( <div> <div> <label htmlFor="firstName">First Name</label> <input id="firstName" type="text" /> </div> </div> ); }

We have to use htmlFor instead of for in React.

The htmlFor property is not React.js specific, it's also used in browsers to programmatically set the for attribute.

If you have some accessibility linting rules in place, you might have to wrap your input tag with your label.

export default function App() { return ( <div> <label htmlFor="firstName"> First Name <input id="firstName" type="text" /> </label> </div> ); }
The reason we have to use htmlFor in React is because the for keyword is a reserved word - it's used in for loops.

If you use the for prop instead of htmlFor, you would get a warning in the Console tab of your developer tools.

export default function App() { // ⛔️ Warning: Invalid DOM property `for`. Did you mean `htmlFor`? return ( <div> <div> <label for="firstName">First Name</label> <input id="firstName" type="text" /> </div> </div> ); }

The same is the reason behind using the className prop instead of class. The word class is reserved because it's used to declare an ES6 class.

export default function App() { // 👇️ use className for styling (not class) return ( <div> <div> <label className="my-label-class" htmlFor="firstName"> First Name </label> <input className="my-input-class" id="firstName" type="text" /> </div> </div> ); }
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.