Menu

Two `<FormField>`s, One `id`. `useId` Stops Them From Colliding.
📰

Two `<FormField>`s, One `id`. `useId` Stops Them From Colliding.

DEV Community: react·Parsa J·about 8 hours ago
#aFHT1ZDh
#devtoreact#devto#dev#label#react
Long article (1357 words) — no AI summary yet.
Reading 0:00
15s threshold

A design system component passes its accessibility audit in isolation. Put two <FormField> s on the same settings page — say, "Email" and "Backup email" — and the audit tool flags the second one: label not associated with its control. Click the first label and the first input focuses, exactly like it should. Click the second label and nothing happens.

Open the DOM and the bug is sitting right there: both inputs have id="field-input" . Both labels have for="field-input" . The browser can only point a for attribute at one element with that id, so it picks the first one it finds — every other instance of the component on the page is invisible to its own label.

The hardcoded id was never going to survive two instances

Here's the component, written the way a first draft usually looks:

function FormField ( { label , type = "text" } ) { return ( < div className = "field" > < label htmlFor = "field-input" > { label } </ label > < input id = "field-input" type = { type } /> </ div > ) ; }

Enter fullscreen…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.