React: Using a ref to set the htmlfor prop of an input's label

Created on 2 Dec 2016  路  2Comments  路  Source: facebook/react

I don't know if this is currently possible, but I believe it would be useful to be able to use refs rather than ids when setting the htmlfor prop of a label.

Something along the lines of...

<input
  ref={(node) => {
    this.input = node;
  }}
/>
<label
  htmlfor={this.input}
/>

Is this something that's previously been considered, or that's currently possible?

Most helpful comment

You would get the benefit of having React be responsible for generating the unique id instead of manually doing it yourself. If there are multiple forms on a page, and in cases where an id isn't useful for anything but the label, it'd be great if React could take a ref for htmlFor and automatically handle the iding.

All 2 comments

@joshfarrant the issue with that is htmlFor is meant to reference the id attribute of aninput element. React would have to read the input instance's id prop and pass it to the label, but what happens when you pass it a node that doesn't have an id? At that point, you'd have to add an id to the input element anyway and there doesn't seem to be a clear advantage over just passing in the id in the first place.

You would get the benefit of having React be responsible for generating the unique id instead of manually doing it yourself. If there are multiple forms on a page, and in cases where an id isn't useful for anything but the label, it'd be great if React could take a ref for htmlFor and automatically handle the iding.

Was this page helpful?
0 / 5 - 0 ratings