use-id

Generate memoized random id
Import

Usage

use-id generates random id that persists across renders. Hook is usually used to bind input elements to labels. Generated random id is saved to ref and will not change unless component is unmounted.

import { useId } from '@mantine/hooks';
function Input({ id }) {
const uuid = useId(id);
return (
<>
<label htmlFor={uuid}>Input label</label>
<input type="text" id={uuid} />
</>
);
}
// input and label will have id 'my-id'
const withId = <Input id="my-id" />;
// input and label will have random id 'mantine-fZMoF'
const withoutId = <Input />;

API

use-id hook accepts two arguments:

  • id – string value that is returned by default
  • generateId – function that is used to generate random id

Hook returns string value that is either id (if first argument is passed) or random id generated with generateId function.

Definition

function useId(id: string, generateId?: () => string): string;
Build fully functional accessible web applications faster than ever
Feedback
Your feedback is most valuable contribution to the project, please share how you use Mantine, what features are missing and what is done good
Leave feedback