Unique HTML IDs in React - now as a module
I have now made an NPM module that solves the problem of getting unique IDs for HTML DOM elements. The module is still lacking proper server-side rendering support, but is otherwise a drop-in solution to get IDs for DOM elements.
class MyComponent extends React.Component {
constructor() {
super()
enableUniqueIds(this)
}
render() {
// Get unique IDs for HTML DOM elements.
// an entirely automatic one or via a key unique to this
// instance of the component.
return (
<form>
<div className="form-group" key={index}>
<label htmlFor={this.nextUniqueId()}>
<input id={this.lastUniqueId()}
type="text"
className="control" />
</div>
<div className="form-group">
<label htmlFor={this.getUniqueId('input')}>Name</label>
<div className="help-block"
id={this.getUniqueId('help')}>
This should be your full name.
</div>
<input id={this.getUniqueId('input')}
type="text"
aria-describedby={this.getUniqueId('help')}
className="control" />
</div>
</form>
)
}
}
You can install the module via npm: npm install --save-dev react-html-id