Invalid DOM property `for` warning in React [Solved]


Borislav Hadzhiev

Last updated: Apr 20, 2022


Photo from Unsplash

Invalid DOM property for warning in React [Solved] #

To fix the React.js warning "Invalid DOM property for. Did you mean htmlFor", use the htmlFor prop instead of for on your label tags. The htmlFor prop is used because for is a reserved word in JavaScript.

invalid dom property for

Here is an example of how the warning is caused.

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

The issue in the code sample is that we're using the for prop to match the label tag to the input, however for is a reserved word in JavaScript.

To get rid of the warning, we have to use htmlFor instead of for.

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

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.

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.

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.