Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / React

Creating Labels for Input Elements in React

5.00/5 (3 votes)
13 Jun 2018CPOL 35.4K  
A quick tip on adding labels to React form elements

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:

HTML
<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 label to your React forms, you'll just need to do something like this:

HTML
<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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)