Generate random IDs with React
This is a short and simple one.
Sometimes you need to generate a random ID to use in React.
Here’s a stripped back real world example I use on this website.
import { useId } from 'react';
export default function MyInput() {
const id = useId();
return (
<>
<label htmlFor={id}>My label</label>
<input id={id} />
<>
)
}
In HTML, you need to say which <input> your label is for. This is based on theid attribute of the input tag.
In React, we use the htmlFor prop instead of the for attribute used in HTML.
So that’s it. React generates an ID and I set the htmlFor and id props with that.
