How to use useId in React

How to use useId in React

In React, the useId hook is a utility hook that can be used to generate a unique id for elements in a component. This can be useful when you need to associate a label with an input element, for example.

useId Example

import { useId } from "react-id-generator";

function MyComponent() {
	const inputId = useId();
	const labelId = useId();

	return (
			<label htmlFor={labelId}>My Input:</label>
			<input id={inputId} type="text" />

In this example, the useId hook is imported from the react-id-generator library, and it is called twice to generate two unique ids, one for the input and one for the label. The generated ids are stored in the inputId and labelId variables. The generated ids are passed to the id and htmlFor attributes of the input and label elements, respectively, so that the browser can associate the label with the input.

It's also worth mentioning that useId hook has an optional parameter which allows to pass a prefix string to the generated ids. This is useful when you have multiple elements with the same type and you want to identify them, for example:

const inputId = useId("input");
const labelId = useId("label");

This will generate ids like input-1,input-2 and label-1,label-2 respectively.

In summary, useId is a React Hooks that generates unique ids to be used as id and htmlFor attributes in form inputs and labels, allowing to associate them and also it allows to identify the elements using prefixes in the generated ids.