So HTML has this awkward problem that to make label work with input, they need to be linked by a matching id/for (renamed by React to htmlFor) pair.
Here's some simplified code with change handles, etc., skipped:
class CheckboxComponent extends Component {
render() {
let {selected,name,idkey} = this.props;
let id = `checkbox-${idkey}`;
return <div>
<input type="checkbox" id={id} checked={selected}/>
<label htmlFor={id}>{name}</label>
</div>;
}
}
Is there any reasonable way to generate those IDs? There are some options but all of them seem really awkward:
- Pass unique
idkeyall the way - but that means not just this component but every parent, grandparent, etc., using it now needs a uniqueidkey. - Use
Math.random()to generate them - that makesrender()non-deterministic, which feels wrong. - Generate a random key with
Math.random()when component gets created/mounted, sorender()itself would be deterministic. - Just turn that whole container into
<label>and rewrite the CSS a bit to make it work. - Give that
<label>noforat all, instead some kind ofonClickhandler to find sibling<input>with DOM API... That's quite straightforward in jQuery-based code, but quite a bit of a mess in React.
Is one of these solutions actually standard practice? Am I missing something else better?