Labels are often overlooked, but important elements for collecting user inputs in React.
Normally, <label> elements have a for attribute set to input id, so HTML displays label next to the input.
Using HTMLFor to create a label for input in React
Let’s look at a simple React component that renders a <label> element in React.
We have <label> and <input> elements. Label We use htmlFor attribute to associate label element to the input element in React. htmlFor attribute should be set to unique id of the input.
In the live demo, you can see that <label> element is positioned on the left of input elements in React. This is normal for document flow, where elements are arranged from left to right, and from top to bottom. This is also true for label elements with htmlFor attributes in React.
You can use <label> with any type of <input> element, not just text type of input. It’s only important for inputs to have a unique id, and to set htmlFor attribute of the label to that id in React.
It doesn’t make a difference whether you are using functional or class components. Label elements need to have htmlFor attributes in React.
htmlFor vs for in React
At first glance, DOM elements in React look identical to their counterparts in HTML. <h1> elements stay <h1>, <input> elements in HTML are also <input> elements in JSX, and so on. There are small differences though. Usage of htmlFor instead of for is one of those differences.
Using for attribute will result in an error.
The error itself suggests the solution. You need to use htmlFor instead of for attribute to associate a label with an input in React.