Creating labels for input elements in React – DEVELOPPARADISE
13/06/2018

Creating labels for input elements in React

When creating forms in React, you’ll often want to add labels to go with your input elements. If you’re used to doing this in HTML, you’d probably start by entering JSX that looks like this:

<label for="myInput">My Input</label> <input id="myInput" type="text" />

But when you load up a component containing this code, you’ll find that it doesn’t work. This is because React doesn’t have a for property in its label element. Instead, it has an htmlFor property, which matches the property name used by the label element in the HTML DOM. So to add a labels to your React forms, you’ll just need to do something like this:

<label htmlFor="myInput">My Input</label> <input id="myInput" type="text" />

and you’ll end up with the generated HTML you’re expecting. The reason for this is simple: for is a reserved keyword in JavaScript, and since JSX is embedded in JavaScript, it avoids using any of JavaScript’s reserved keywords. This is the same reason that React components use the className attribute instead of class.