In React (Facebook's framework), I need to render a label element bound to a text input using the standard for
attribute.
e.g. the following JSX is used:
<label for="test">Test</label> <input type="text" id="test" />
However, this produces HTML missing the required (and standard) for
attribute:
<label>Test</label> <input type="text" id="test">
What am I doing wrong?
The for attribute specifies which form element a label is bound to.
React has no for property for labels. It defined the htmlFor attribute. The reason is, that you are writing HTML code in JSX syntax. JSX is an extension to javascript which executes javascript code.
Since for is a reserved word in JavaScript, React elements use htmlFor instead.
React provides us some in-built methods that we can override at particular stages in the life-cycle of the component. In class-based components, the htmlFor attribute is used to get the HTML for the given HTML elements.
The for
attribute is called htmlFor
for consistency with the DOM property API. If you're using the development build of React, you should have seen a warning in your console about this.
Yes, for react,
for
becomes htmlFor
class
becomes className
etc.
see full list of how HTML attributes are changed here:
https://facebook.github.io/react/docs/dom-elements.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With