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

Dima Vyshniakov @morewings

About: Front end developer

Location:
Berlin
Joined:
Feb 6, 2020

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

Publish Date: Oct 15 '24
1 0

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!

Comments 0 total

    Add comment