Artem Sapegin Artem Sapegin - 10 days ago 6
React JSX Question

How to generate unique IDs for form labels in React?

I have form elements with

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

React.createClass({
render() {
const id = ???;
return (
<label htmlFor={id}>My label</label>
<input id={id} type="text"/>
);
}
});


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?

Answer

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 (
            <label htmlFor={this.id}>My label</label>
            <input id={this.id} type="text"/>
        );
    }
});

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.