Click here to Skip to main content
15,884,537 members
Articles / Web Development / React
Tip/Trick

Creating Labels for Input Elements in React

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
13 Jun 2018CPOL 34K   1  
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)


Written By
Software Developer My House
Canada Canada
I spent 5 years working for Ottawa startups before returning home to Toronto. During Covid I decided to escape the big city and moved north to Penetanguishene, Ontario.

I'm a .NET/JavaScript/TypeScript developer and technical writer by day, but in the evening you'll often find me cooking up projects in Ruby, Haskell, Clojure, Elixir, and F#.

Comments and Discussions

 
-- There are no messages in this forum --