DEV Community

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

Posted on

1

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)

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!