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 label 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
.
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#.