[docs] Use React.useId() for demo IDs#48300
Conversation
Accordion and menu demos use hardcoded IDs for aria-controls and aria-labelledby. When the same demo appears multiple times on a page, this produces duplicate IDs. Switch to React.useId() to generate unique IDs per instance.
React.useId() for demo IDs
Bundle size
Deploy previewhttps://deploy-preview-48300--material-ui.netlify.app/ Check out the code infra dashboard for more information about this PR. |
React.useId() for demo IDsReact.useId() for demo IDs
|
Oh, I thought we already had an issue for this, created #48305. |
|
FWIW thse also rely on manual |
I'lll take a look, I only fixed the ones that were causing duplicate ids in our html. |
…o IDs Extends the accordion/menu demo fix to the remaining demos that wire hardcoded strings into aria-labelledby / aria-controls / aria-describedby or pair an id with htmlFor. Duplicate IDs would be emitted when these demo snippets are copied into apps and rendered multiple times.
React.useId() for demo IDsReact.useId() for demo IDs
@ZeeshanTamboli True. Now, migrating all the demos from hard-coded IDs to I don't know if this makes the demos more portable, though. There are conflicting forces:
|
Summary
Accordion, menu, radio, select, text-field, and slider demos use hardcoded IDs for
aria-controls/aria-labelledby/aria-describedby/htmlFor. When users copy these snippets into apps and render multiple instances, duplicate IDs end up in the DOM and break assistive tech.Switch to
React.useId()so each rendered instance gets a unique base ID.Relates to mui/mui-public#1241
Pattern
Each demo calls
React.useId()once per logical control and derives all related IDs from it via template literals — even when the control only exposes a single ID. This keeps the shape of the code identical across demos with one ID and demos with several.The alternative — one useId() per ID role, named by role — was considered and rejected. It reads fine for a single-ID case but demos with multiple related IDs end up with a noisy prologue and no common prefix tying the IDs to the same control:
Preview: https://deploy-preview-48300--material-ui.netlify.app/material-ui/react-accordion/