DEV Community

Cover image for How to create React Component with consistent user-configurable HTML id prop
Dima Vyshniakov
Dima Vyshniakov

Posted on

How to create React Component with consistent user-configurable HTML id prop

React 18 introduced useId hook, which allows us to have consistent unique identifiers both on client and server sides. This is particularly useful when working with HTML Global id attribute

This custom hook allows implementing a React component with an optional id prop configurable from outside, but consistent and unique identifier for the component's children. So developers don't have to fill it each time they use the component.

import type {FC} from 'react'
import {useId} from 'react'

const useConsistentId = (idProp?: string) => {
    const backupId = useId();
    return idProp !== undefined ? idProp : backupId;
}

const Component: FC<{id?: string;}>= ({id: idProp}) => {
    const id = useConsistentId (idProp);
    // this is required to make accessible input description
    const hintId = `${id}-hint`;
    return <fieldset>
        <label htmlFor={id}>Clickable label</label>
        <input type="text" id={id} aria-describedby={hintId}/>
        <div id={hintId}>Input description</div>
    </fieldset>
}
Enter fullscreen mode Exit fullscreen mode

Demo

Happy coding!

Top comments (0)