I'm in the process of writing a component wrapping an HTML checkbox element to easily manage the label and make it accessible. I've just learned about JavaScript Symbols and wanted to know if there was any harm in using them as a unique identifier in the for
attribute of a label
. Here is the code of such a component using React:
const Checkbox = ({ label }) => {
const id = Symbol().toString();
return (
<div>
<input type="checkbox" id={id} />
<label htmlFor={id}>{label}</label>
</div>
);
};
symbol
is one of the new data types since ES6 that only represents a unique characteristic while it is still itself
When you .toString()
, the symbols will immediately be forced into a normal string state and will no longer be unique. (Symbol().toString()
always result "Symbol()"
):
Use unique number:
let index = 1;
const Checkbox = ({ label }) => {
const id = '_' + (index++).toString(36)
return (
<div>
<input type="checkbox" id={id} />
<label htmlFor={id}>{label}</label>
</div>
);
};