Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React ignores 'for' attribute of the label element

Tags:

reactjs

label

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?

like image 241
goofballLogic Avatar asked Mar 31 '14 01:03

goofballLogic


People also ask

What React attribute allows you to specify which form element a label is bound to?

The for attribute specifies which form element a label is bound to.

How do you define a label in React?

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.

What is the alternative of for attribute in React for input element?

Since for is a reserved word in JavaScript, React elements use htmlFor instead.

Why we use htmlFor in React?

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.


2 Answers

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.

like image 186
Sophie Alpert Avatar answered Sep 20 '22 13:09

Sophie Alpert


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

like image 29
Derrick Avatar answered Sep 17 '22 13:09

Derrick