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

avatar

Borislav Hadzhiev

Sat Apr 23 20222 min read

banner

Photo by Chad Madden

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.

App.js
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.

App.js
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.

App.jsa
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.

App.js
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> ); }
Use the search field on my Home Page to filter through my more than 1,000 articles.