useId
を使用すると以下のように一意のIDを設定できます。
同一画面に同じコンポーネントを複数回使用してもIDが重複することはありません。
import { useId } from 'react';
export default function Form() {
const id = useId();
return (
<form>
<label htmlFor={`${id}-firstName`}>First Name:</label>
<input id={`${id}-firstName`} type="text" />
<hr />
<label htmlFor={`${id}-lastName`}>Last Name:</label>
<input id={`${id}-lastName`} type="text" />
</form>
);
}