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!

πŸ‘‹ While you are here

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

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!

πŸ‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay