Accessible composite TextField component
accessible composition and prop forwarding.
associate label and input via matching for and id, generate a unique id, spread remaining props onto the native input.
a label not tied to the input, or swallowing native props.
WHAT THIS TESTS Whether you can compose a labelled input that is accessible by default and remains a flexible wrapper over the native input.
A GOOD ANSWER COVERS Associate the label and input explicitly. Give the input a unique id and set the label's for attribute to that id, or wrap the input inside the label element. Either creates a programmatic association so clicking the label focuses the input and assistive tech reads the label as the input's accessible name. Generate the id automatically, using a stable unique-id hook or utility, so rendering several TextFields does not produce duplicate ids. For prop forwarding, accept the component's own props, like label text, helper text, and error, then spread the remaining props onto the native input so consumers can pass type, placeholder, required, value, onChange, and any other native attribute without you enumerating each. Link helper and error messages with aria-describedby, and reflect invalid state with aria-invalid.
COMMON WRONG ANSWERS Rendering a label not tied to the input, so clicking it does nothing and screen readers miss the name. Hardcoding a single id, which collides when the field is reused. Swallowing native props so consumers cannot set type or required. Using placeholder as a substitute for a label, which disappears on input.
LIKELY FOLLOW-UPS How do you expose the underlying input for refs? Forward a ref to the native input. How do you announce errors? aria-describedby plus aria-invalid and a live region if needed. Wrapping versus for/id? for/id is more flexible for layout.
ONE CONCRETE EXAMPLE The TextField generates id field-3, renders a label with for set to field-3 and an input with that id. Clicking the label focuses the input. The component pulls off label and error, then spreads the rest, so a caller passing type email and required has those applied to the real input. An error message gets an id referenced by the input's aria-describedby.
Read the original → developer.mozilla.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.