Invalid DOM property `for`. Did you mean `htmlFor`

The React error “Invalid DOM property `for`. Did you mean `htmlFor`” occurs when you use the ‘for’ as an attribute in JSX to associate a label with a form control, but in the JavaScript, ‘for’ is a reserved keyword and it cannot be used as an attribute.

To solve this error use the ‘htmlFor’ attribute instead of the ‘for’ attribute in JSX.

Here is an example that throws an error.

function MyForm() {
  	return (
    	<form>
    		{/* This line throws error: "Invalid DOM property for. Did you mean htmlFor?"  */} 
      		<label for="emailInput">Email:</label>
      		<input type="email" id="emailInput" name="email" />
    	</form>
  	);
}

The error is coming from for="emailInput" in the element <label>. Instead ‘for’ use ‘htmlFor’ as given below.

function MyForm() {
  	return (
    	<form>
      		<label htmlFor="emailInput">Email:</label>
      		<input type="email" id="emailInput" name="email" />
    	</form>
  	);
}

We can remove the error "Invalid DOM property `for`. Did you mean `htmlFor`" by using htmlFor instead of for in JSX.

Similarly, the ‘class’ is also a reserved keyword in JSX. So you should use the className attribute instead of the class attribute to apply CSS classes to an element. Since ‘class’ is a reserved keyword in JavaScript, you cannot use ‘class’ as an attribute name.

Please look into the below example.

<label htmlFor="emailInput" class="form-label">Email:</label>

Above code will throw an error: Invalid DOM property `class`. Did you mean `className`?

To solve the error, we have to use ‘className’ instead of ‘class’ as given below.

<label htmlFor="emailInput" className="form-label">Email:</label>

Conclusion

To solve the error “Invalid DOM property `for`. Did you mean `htmlFor`” use the ‘htmlFor’ attribute instead of the ‘for’ attribute. Because the ‘for’ attribute is a reserved keyword in react. Similarly ‘class’ is also a reserved keyword, so use ‘className’ instead of ‘class’ in JSX.