Enforcing an accessible name on icon-only buttons
API design that guarantees an accessible name.
require aria-label via the type system for icon-only variants, warn at runtime, decorate the icon as aria-hidden.
trusting developers to remember a label on icon buttons.
WHAT THIS TESTS This checks whether you design APIs that make accessibility failures impossible or at least loud, rather than relying on developer discipline.
A GOOD ANSWER COVERS Distinguish the two shapes in the type system. A text button derives its accessible name from its text children, so no extra prop is needed. An icon-only button has no text, so it must carry an explicit name. Model this with a TypeScript discriminated union: when children are an icon with no text, or when an iconOnly prop is set, the props type requires aria-label or aria-labelledby, so omitting it is a compile-time error rather than a silent runtime gap. As a backstop for JavaScript consumers and dynamic cases, emit a development-mode console warning when a button renders with no discernible accessible name. Mark the icon itself aria-hidden true (or role presentation) so screen readers announce the label, not the icon glyph or its title. Optionally support a tooltip that shares the same label string to avoid duplication.
COMMON WRONG ANSWERS Making aria-label always optional and documenting that icon buttons need it, which developers forget. Letting the icon's own title or alt leak as the name unpredictably. Putting the label only in a tooltip that screen readers may not read. No compile-time or runtime enforcement at all.
LIKELY FOLLOW-UPS How do discriminated unions encode this requirement. Why mark the icon aria-hidden. How do you keep the tooltip and accessible name in sync.
ONE CONCRETE EXAMPLE Button props are typed so passing only an icon with no aria-label fails the TypeScript build; once a developer adds aria-label Close, the icon is aria-hidden, and a screen reader announces Close button, while a text button needs no label at all because its children supply the name.
Read the original → w3.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.