React Reference ยท Props and Attributes
React htmlFor prop
Reference for htmlFor in React: link a label to a form control by id, use useId for unique ids, and know when wrapping the input makes htmlFor unnecessary.
htmlFor is the JSX name of the HTML for attribute on <label>. Its value is the id of the form control the label describes. Connecting the two matters for accessibility and usability: screen readers announce the label when the control gets focus, and clicking the label focuses the input or toggles the checkbox, which gives people a much larger click target.
The name differs from HTML because for is a reserved word in JavaScript, and React's props follow the DOM property (label.htmlFor). Using for still works in React 19 but logs a warning.
<label htmlFor="email">Email</label> <input id="email" type="email" />
Try it
Syntax
<label htmlFor="control-id">Text</label> <input id="control-id" />
| Name | Description |
|---|---|
htmlFor |
The id of a labelable element: <input> (except type="hidden"), <select>, <textarea>, <button>, <meter>, <output> or <progress>. |
id (on the control) |
Must exactly match htmlFor and be unique in the document. |
Returns: a <label> rendered with a for attribute.
Errors: none thrown. Using for logs Invalid DOM property for. Did you mean htmlFor?. A label whose htmlFor matches no element does nothing, silently.
Usage notes
- Wrapping works without
htmlFor. A control nested inside its label (<label>Name <input /></label>) is associated automatically, noidneeded. UsehtmlForwhen label and input are separate in the layout. - Use
useIdin reusable components. A hard-codedid="name"breaks as soon as the component renders twice. Hard-coded ids are fine in one-off pages. - Do not use
useIdoutput in CSS selectors. The generated string contains characters that are awkward in selectors, and its exact format changes between React versions. Use class names for styling. - One control, one label. A control can have several labels, but a label points to only one control.
- A placeholder is not a label. It disappears while typing and is often not announced. Keep a visible label.
- Clicking a label fires a synthetic click on its control. If both have
onClickhandlers, the handler may run twice (once for the label click, once for the redirected click on the control). PreferonChangefor inputs. - Group controls (radio buttons, checkboxes) with
<fieldset>and<legend>, and label each option individually. - Other
for-like props.<output>also supportshtmlFor, taking a space-separated list of ids of the elements that contribute to its value.
Related
<input>,<select>,<textarea>, useId, aria-* attributes- Lessons: Forms and inputs, Accessibility