Click here to Skip to main content
13,597,784 members
Click here to Skip to main content
Add your own
alternative version

Stats

1.7K views
1 bookmarked
Posted 13 Jun 2018
Licenced CPOL

Creating Labels for Input Elements in React

, 13 Jun 2018
Rate this:
Please Sign up or sign in to vote.
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:

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

License

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

Share

About the Author

Ryan Peden
Software Developer CodeProject
Canada Canada
I spent 5 years working for Ottawa startups before returning home to Toronto and landing at CodeProject.

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

You may also be interested in...

Pro
Pro

Comments and Discussions

 
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web03-2016 | 2.8.180621.3 | Last Updated 13 Jun 2018
Article Copyright 2018 by Ryan Peden
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid