@piplup/utilsHooks
useId
React hook that returns an id prop when one is passed, or a generated unique ID.
useId returns idProp when it is passed, and otherwise a unique ID from React's built-in useId. Components can accept an id prop and still have an ID to wire up htmlFor and aria-* attributes when it isn't passed.
import { useId } from "@piplup/utils";
function TextField({ id, label, hint }: { id?: string; label: string; hint: string }) {
const inputId = useId(id);
const hintId = `${inputId}-hint`;
return (
<div>
<label htmlFor={inputId}>{label}</label>
<input id={inputId} aria-describedby={hintId} />
<p id={hintId}>{hint}</p>
</div>
);
}React's useId is still called when idProp is passed, so the hook can be called unconditionally, and the generated ID stays the same on the server and the client.
This hook has the same name as React's useId. If a file needs both, rename one on import: import { useId as useIdProp } from "@piplup/utils".
Parameters
Prop
Type
Return value
string: idProp, or a generated ID that is unique within the React tree.