HiveBrain v1.2.0
Get Started
← Back to all entries
snippetreactMajor

How to generate unique IDs for form labels in React?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
idsuniquegeneratereactlabelsforformhow

Problem

I have form elements with labels and I want to have unique IDs to link labels to elements with htmlFor attribute. Something like this:

React.createClass({
    render() {
        const id = ???;
        return (
            My label
            
        );
    }
});


I used to generate IDs based on this._rootNodeID but it’s unavailable since React 0.13. What is the best and/or simplest way to do it now?

Solution

This solutions works fine for me.

utils/newid.js:

let lastId = 0;

export default function(prefix='id') {
    lastId++;
    return `${prefix}${lastId}`;
}


And I can use it like this:

import newId from '../utils/newid';

React.createClass({
    componentWillMount() {
        this.id = newId();
    },
    render() {
        return (
            My label
            
        );
    }
});


But it won’t work in isomorphic apps.

Added 17.08.2015. Instead of custom newId function you can use uniqueId from lodash.

Updated 28.01.2016. It’s better to generate ID in componentWillMount.

Code Snippets

let lastId = 0;

export default function(prefix='id') {
    lastId++;
    return `${prefix}${lastId}`;
}
import newId from '../utils/newid';

React.createClass({
    componentWillMount() {
        this.id = newId();
    },
    render() {
        return (
            <label htmlFor={this.id}>My label</label>
            <input id={this.id} type="text"/>
        );
    }
});

Context

Stack Overflow Q#29420835, score: 97

Revisions (0)

No revisions yet.