UI Component Implementation: Forms and States Questions
Implementing forms and the non-happy-path states of UI components in the browser. Covers form building (controlled and uncontrolled inputs, reusable form hooks tracking values, touched fields and errors, dynamic groups of repeating fields, multi-step flows, submit handling), client-side and server-side validation (inline errors, validation timing, cross-field rules, async validation such as username checks with stale-response handling, error summaries, mapping API error responses onto fields), and the states a component must handle: loading and pending, error and retry, empty results, disabled, error boundaries around a failing widget, and edge cases such as double submit, slow or failed networks, drafts preserved across failures, and unexpected input like pasted text or locale differences. Includes building custom inputs and widgets robustly: restricted numeric inputs, comboboxes and custom selects, and date fields with calendar popups, with labels, error association, focus management, announcing errors to assistive technology and keyboard operation. Excludes design-system library governance and tokens, optimistic-update and rollback logic in the client data layer, accessibility strategy as a design practice, and the state-management architecture of the whole application.
Build a numeric input component in React that only accepts whole numbers from 0 to 100 and passes a clean value to its parent. What do you do about pasted text, an empty field, a leading minus sign or decimal point, and the cursor jumping while the user types?
Sample Answer
Direct answer
Do not rely on <input type="number"> for a whole-number field. Use type="text" with inputMode="numeric" (which asks mobile browsers for a digit keypad), keep what the user sees in a string called the draft (in React terms this is a controlled input: React state, not the browser, owns the text, and the input shows whatever value it is given), and run every change through one clean() function that keeps only digits, caps the length at three, and strips leading zeros. The component reports a number to its parent only when the draft is a whole number from 0 to 100, and null when the field is empty or out of range. Pasted text is handled in an onPaste handler, and the caret (the blinking insertion point) is put back after a rejected keystroke.
Why not type="number"
MDN's page for the number input says its implicit role (the accessibility role the browser assigns with no ARIA attribute) is spinbutton, the role for a control that steps a number up and down, and advises against the type if spinbutton behaviour is not important: there is a risk of users accidentally incrementing the number while doing something else (the mouse wheel and the arrow keys are the usual ways), and when they enter something that is not a number there is no explicit feedback about what they did wrong. Typing 1e into a number input leaves value as the empty string while validity.badInput (a built-in flag that is true when the browser holds typed text it cannot turn into a number) is true (output below), so value cannot tell "empty" from "garbled". MDN's suggested alternative for digit-only data is type="text" with inputmode="numeric" and a pattern (an attribute holding a regular expression the value must match). Note that pattern does not enforce a range, so the 0 to 100 limit still has to be checked in JavaScript, and again on the server.
How each case is handled
| Input case | Behaviour | Why |
|---|---|---|
Letters, -, . typed | Removed by clean(); the field text does not change | The sign and decimal point can never be part of a whole number from 0 to 100. |
| Pasted text | Handled in onPaste with preventDefault(). Only a string of digits is accepted (spliced in at the selection, then cleaned). Anything else (for example abc12x or 1.5) is refused with a message | Silently stripping 1.5 to 15 would change the user's number to a different one. Refusing is honest; the message is linked with aria-describedby. |
| Empty field | Parent receives null, no error shown | An empty field is a normal state while typing, not an error. |
| Leading zeros | 007 becomes 7; a single 0 stays 0 | Zero is a legitimate value. The code compares with null and never tests truthiness, because 0 is falsy in JavaScript and if (value) would treat it as "no value". |
Above 100 (150) | Field keeps the digits, shows an error, parent receives null | Typing 150 passes through 15, so the field must not block the third digit; a stale 15 must not stay with the parent. |
| Caret jumping | Restored after the event (explained below) | See below. |
The caret problem, precisely
The rule to hold on to: after a rejected keystroke the cleaned text equals what React already holds, but the browser's copy contains the stray character, so React rewrites the input and the caret lands at the end. clean(raw, caret) is what computes the right position. Traced with real values (raw is the text in the input right after the keystroke, caret is its caret index):
| Step | clean('1x2', 2): user typed x between 1 and 2 | clean('00x5', 3): user typed x after two zeros |
|---|---|---|
digitsBefore (digits in raw.slice(0, caret)) | '1' | '00' |
text (all digits, first 3) | '12' | '005' |
| after stripping leading zeros | '12', removedLeading = 0 | '5', removedLeading = 2 |
| caret = digitsBefore.length - removedLeading, clamped to 0..text.length | 1 - 0 = 1 | 2 - 2 = 0 |
So the caret goes back between the 1 and the 2 in the first case, and to the very start of 5 in the second. Run in a node:22 container, clean('1x23', 2) returns text 123 with caret 1, the same way.
When the user types a rejected character in the middle of the text, the browser first inserts it (1x2), React runs onChange, the cleaned value (12) equals the state, and at the end of the event React writes the state back into the input. Assigning a value to an input moves the caret to the end of the text whenever the new string differs from the current one. The next script (Playwright 1.48.2, run in the mcr.microsoft.com/playwright:v1.48.2-jammy container) checks the caret-reset rule and the number-input behaviour mentioned above in three engines; the tests after the component check the finished component.
import { chromium, firefox, webkit } from 'playwright';
for (const [name, type] of [['chromium', chromium], ['firefox', firefox], ['webkit', webkit]]) {
const browser = await type.launch();
const page = await browser.newPage();
await page.setContent('<input id="n" type="text">');
const r = await page.evaluate(() => {
const el = document.getElementById('n');
const out = {};
el.value = '1x23';
el.setSelectionRange(2, 2); // caret just after the stray "x"
el.value = '1x23'; // same string assigned again
out.sameValue = el.selectionStart;
el.value = '123'; // different string assigned
out.differentValue = el.selectionStart;
return out;
});
console.log(name, 'text input caret', JSON.stringify(r));
await page.setContent('<input id="num" type="number">');
await page.focus('#num');
await page.keyboard.type('1e');
const num = await page.evaluate(() => {
const el = document.getElementById('num');
return { value: el.value, badInput: el.validity.badInput };
});
console.log(name, 'number input after typing "1e"', JSON.stringify(num));
await browser.close();
}
It printed:
chromium text input caret {"sameValue":2,"differentValue":3}
chromium number input after typing "1e" {"value":"","badInput":true}
firefox text input caret {"sameValue":2,"differentValue":3}
firefox number input after typing "1e" {"value":"","badInput":true}
webkit text input caret {"sameValue":2,"differentValue":3}
webkit number input after typing "1e" {"value":"","badInput":true}
For an input holding 1x23 with the caret at 2, assigning the identical string leaves the caret at 2, and assigning 123 moves it to 3, the end, in all three engines. So the fix is to compute where the caret should sit in the cleaned text (count the digits before the caret in the raw text, minus any leading zeros removed) and call setSelectionRange in a microtask (a small job that runs right after the current event handler finishes), which is after React's write-back.
The component
import { useId, useRef, useState, type ChangeEvent, type ClipboardEvent } from 'react';
const MAX = 100;
// Keep digits only, at most 3 of them, and drop leading zeros ("007" -> "7", "0" stays "0").
// Also reports where the caret should sit afterwards, counted in the cleaned string.
function clean(raw: string, caret: number): { text: string; caret: number } {
const digitsBefore = raw.slice(0, caret).replace(/\D/g, '');
let text = raw.replace(/\D/g, '').slice(0, 3);
const stripped = text.replace(/^0+(?=\d)/, '');
const removedLeading = text.length - stripped.length;
text = stripped;
return { text, caret: Math.max(0, Math.min(digitsBefore.length - removedLeading, text.length)) };
}
export function WholeNumberInput({
label,
onChange,
restoreCaret = true,
}: {
label: string;
onChange: (value: number | null) => void; // null means "no valid number right now"
restoreCaret?: boolean;
}) {
const id = useId();
const input = useRef<HTMLInputElement>(null);
const [draft, setDraft] = useState('');
const [message, setMessage] = useState('');
function commit(text: string, caret: number) {
const n = text === '' ? null : Number(text);
const tooBig = n !== null && n > MAX;
setDraft(text);
setMessage(tooBig ? `Enter a whole number from 0 to ${MAX}.` : '');
// React writes the (possibly unchanged) state back into the input at the end of the event, and the
// browser then moves the caret to the end. A microtask runs after that, so put the caret back there.
if (restoreCaret) queueMicrotask(() => input.current?.setSelectionRange(caret, caret));
onChange(n === null || tooBig ? null : n); // 0 is a real value: compare with null, never test truthiness
}
function handleChange(e: ChangeEvent<HTMLInputElement>) {
const el = e.target;
const { text, caret } = clean(el.value, el.selectionStart ?? el.value.length);
commit(text, caret);
}
function handlePaste(e: ClipboardEvent<HTMLInputElement>) {
e.preventDefault(); // we decide what a paste means; the browser's default would splice raw text in
const pasted = e.clipboardData.getData('text').trim();
if (!/^\d+$/.test(pasted)) {
setMessage('Paste a whole number such as 42.');
return;
}
const el = e.currentTarget;
const start = el.selectionStart ?? draft.length;
const end = el.selectionEnd ?? draft.length;
const raw = draft.slice(0, start) + pasted + draft.slice(end);
const { text, caret } = clean(raw, start + pasted.length);
commit(text, caret);
}
return (
<div>
<label htmlFor={id}>{label}</label>
<input
id={id}
ref={input}
type="text"
inputMode="numeric"
autoComplete="off"
value={draft}
aria-invalid={message ? true : undefined}
aria-describedby={message ? `${id}-msg` : undefined}
onChange={handleChange}
onPaste={handlePaste}
/>
{message && <p id={`${id}-msg`}>{message}</p>}
</div>
);
}
The tests
They run in a jsdom environment (a simulated browser DOM for Node), created by the dom-env.mjs file listed under Running the code at the end.
import '../dom-env.mjs';
import assert from 'node:assert/strict';
import { render, screen, cleanup } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { WholeNumberInput } from './WholeNumberInput.tsx';
const user = userEvent.setup();
let reported: (number | null)[] = [];
const last = () => reported[reported.length - 1];
function mount(restoreCaret = true) {
cleanup();
reported = [];
render(<WholeNumberInput label="Score" restoreCaret={restoreCaret} onChange={(v) => reported.push(v)} />);
return screen.getByLabelText('Score') as HTMLInputElement;
}
let input = mount();
await user.type(input, '12');
assert.equal(input.value, '12');
assert.equal(last(), 12);
console.log('type "12" -> field', JSON.stringify(input.value), '| parent', last());
input = mount();
await user.type(input, 'ab-.c');
assert.equal(input.value, '');
assert.equal(last() ?? null, null);
console.log('type "ab-.c" -> field', JSON.stringify(input.value), '| parent', last() ?? null);
input = mount();
await user.click(input);
await user.paste('abc12x');
assert.equal(input.value, '');
assert.match(screen.getByText(/whole number such as 42/).textContent!, /42/);
await user.paste('1.5');
assert.equal(input.value, '');
await user.paste('42');
assert.equal(input.value, '42');
assert.equal(last(), 42);
assert.equal(screen.queryByText(/Paste a whole number/), null);
console.log('paste abc12x, 1.5, 42 -> field', JSON.stringify(input.value), '| parent', last());
input = mount();
await user.type(input, '150');
assert.equal(last(), null);
assert.equal(input.getAttribute('aria-invalid'), 'true');
console.log('type "150" -> field', JSON.stringify(input.value), '| parent', last(), '|', screen.getByText(/Enter a whole number/).textContent);
input = mount();
await user.type(input, '0');
assert.equal(last(), 0);
await user.clear(input);
assert.equal(last(), null);
await user.type(input, '007');
assert.equal(input.value, '7');
assert.equal(last(), 7);
console.log('"0" -> parent 0; cleared -> parent null; "007" -> field', JSON.stringify(input.value));
// Caret: type a stray letter between "1" and "2".
async function caretAfterStrayLetter(restore: boolean) {
const el = mount(restore);
await user.type(el, '12');
await user.type(el, 'x', { initialSelectionStart: 1, initialSelectionEnd: 1 });
assert.equal(el.value, '12');
return el.selectionStart;
}
const withRestore = await caretAfterStrayLetter(true);
const withoutRestore = await caretAfterStrayLetter(false);
assert.equal(withRestore, 1);
assert.equal(withoutRestore, 2); // the control: without the fix the caret jumps to the end
console.log('stray "x" typed after the 1 of "12": caret with fix =', withRestore, '| without fix =', withoutRestore);
Run in a node:22 container (node --import tsx numeric/numeric.test.tsx, React 18.3.1, user-event 14.6.7, jsdom 25), it prints:
type "12" -> field "12" | parent 12
type "ab-.c" -> field "" | parent null
paste abc12x, 1.5, 42 -> field "42" | parent 42
type "150" -> field "150" | parent null | Enter a whole number from 0 to 100.
"0" -> parent 0; cleared -> parent null; "007" -> field "7"
stray "x" typed after the 1 of "12": caret with fix = 1 | without fix = 2
The last line is the control: the same keystrokes with restoreCaret={false} leave the caret at 2, so the assertion that expects 1 fails without the fix. tsc --noEmit reports no errors.
The same behaviour in real browsers
jsdom mimics the caret rule; real engines are checked by bundling the component with esbuild (npx esbuild numeric/browser-entry.tsx --bundle --outfile=numeric-bundle.js) and driving the bundle with Playwright 1.48.2. The entry file renders the component into a div with id root and records the value it reports:
import { createRoot } from 'react-dom/client';
import { WholeNumberInput } from './WholeNumberInput.tsx';
declare global { interface Window { lastValue: number | null } }
createRoot(document.getElementById('root')!).render(
<WholeNumberInput label="Score" onChange={(v) => (window.lastValue = v)} />,
);
The Playwright script (the page is given an empty div#root, the bundle is injected, and the input is found by its label):
import { chromium, firefox, webkit } from 'playwright';
import { readFileSync } from 'node:fs';
const bundle = readFileSync('numeric-bundle.js', 'utf8');
for (const [name, type] of [['chromium', chromium], ['firefox', firefox], ['webkit', webkit]]) {
const browser = await type.launch();
const page = await browser.newPage();
await page.setContent('<div id="root"></div>');
await page.addScriptTag({ content: bundle });
const input = page.getByLabel('Score');
await input.click();
await page.keyboard.type('12');
await page.keyboard.press('ArrowLeft'); // caret between 1 and 2
await page.keyboard.type('x');
const state = await input.evaluate((el) => ({ value: el.value, caret: el.selectionStart }));
await page.keyboard.type('9'); // a digit typed at the caret still lands there
const after = await input.evaluate((el) => ({ value: el.value, caret: el.selectionStart }));
console.log(name, JSON.stringify(state), JSON.stringify(after), 'parent =', await page.evaluate(() => window.lastValue));
await browser.close();
}
In the mcr.microsoft.com/playwright:v1.48.2-jammy container it printed:
chromium {"value":"12","caret":1} {"value":"192","caret":2} parent = null
firefox {"value":"12","caret":1} {"value":"192","caret":2} parent = null
webkit {"value":"12","caret":1} {"value":"192","caret":2} parent = null
After typing 12, moving the caret between the digits and typing x, the field still holds 12 with the caret at 1. Typing 9 then lands at the caret and gives 192, which is above 100, so the parent receives null. (WebKit in Playwright is the engine, not Safari on iOS.)
Complexity and edge cases
clean() is O(n) in the input length, and n is at most the length of whatever was pasted. Edge cases covered: paste into a selection (it replaces the selected text), and a parent that needs to reset the field (give the component a new key; the draft lives inside it). Cases that need extra work: a different range or a minimum above 0 (an intermediate draft like 1 toward 10 must not be reported as an error while typing, so below-minimum checks belong on blur), and thousands separators or locale digits, which \D would strip.
Pitfalls
- Debouncing the sanitising: the field would briefly show characters it will later reject.
- Storing the parsed number as the only state:
""and"0"and"00"collapse into the same thing and the field fights the user. - Validating only in the browser: the server must reject out-of-range values as well.
Running the code
Everything runs from one project root in a node:22 container. Files: dom-env.mjs, package.json, tsconfig.json and numeric/WholeNumberInput.tsx, numeric/numeric.test.tsx, numeric/browser-entry.tsx and the two Playwright scripts above saved as numeric/pw-caret.mjs (the first) and numeric/pw-browser.mjs (the second).
npm i react@18.3.1 react-dom@18.3.1 @testing-library/react@16 @testing-library/dom@10 @testing-library/user-event@14 jsdom@25 tsx typescript@5 @types/react@18 @types/react-dom@18 @types/node@22 esbuild
node --import tsx numeric/numeric.test.tsx
npx esbuild numeric/browser-entry.tsx --bundle --outfile=numeric-bundle.js
npx tsc --noEmit
dom-env.mjs (copies the jsdom window's globals onto Node's global object):
import { JSDOM } from 'jsdom';
const { window } = new JSDOM('<!doctype html><body></body>', { url: 'http://localhost/', pretendToBeVisual: true });
for (const k of Object.getOwnPropertyNames(window)) if (!(k in globalThis)) Object.defineProperty(globalThis, k, { configurable: true, get: () => window[k] });
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
package.json:
{ "type": "module" }
tsconfig.json:
{"compilerOptions":{"jsx":"react-jsx","strict":true,"module":"esnext","moduleResolution":"bundler","target":"es2022","allowImportingTsExtensions":true,"noEmit":true,"skipLibCheck":true}}
Without "type": "module" the test does not compile (esbuild, used by tsx, reports Top-level await is currently not supported with the "cjs" output format); without "jsx": "react-jsx" the JSX becomes React.createElement calls and the run stops with ReferenceError: React is not defined.
The two Playwright scripts run in the mcr.microsoft.com/playwright:v1.48.2-jammy container, in the same project after npm i playwright@1.48.2: node numeric/pw-caret.mjs, and, after the esbuild command, node numeric/pw-browser.mjs.
A form-heavy single-page app talks to an API that returns errors shaped like { error: { code: 'invalid_field', message: 'Invalid email', fields: { email: 'invalid_format' } } }. How do you turn those responses into what the user sees: per-field errors, form-level errors, translated text, and the difference between failures worth retrying and ones that are not? What do you do with server messages you do not want to show verbatim?
Sample Answer
Treat the server response as data, never as display text. Parse it into a small view model (a plain object holding exactly what the screen needs: field errors, an optional form-level error, a retryable flag) and render only strings from your own message catalog (a lookup table from keys to user-facing text, one table per language), chosen by the machine-readable code values. The server's message goes to logs, not to the screen.
Mapping layers
Take the response { error: { code: 'invalid_field', message: 'Invalid email', fields: { email: 'invalid_format' } } } through four steps:
- Get a result at all.
fetchrejects its promise only when the request fails outright (for example a network error); an HTTP 4xx or 5xx resolves normally and must be detected fromresponse.ok/response.status(MDN,Window.fetch()). So the wrapper turns a rejection into{ networkError: true }and a non-2xx response into{ status, body, retryAfter }. The body parse is wrapped intry/catchbecause proxies and gateways (servers that sit between the browser and the application and forward requests) often answer a 502 with an HTML page, not JSON. - Per-field errors. Each entry of
fieldsis a field name plus a code. Look up the text by the most specific key first (email.invalid_format), then by the bare code (required), then a generic "check this field" string. A field name the form does not render (the server blameszip, the UI has no zip input; the code calls these "orphans") cannot be shown beside an input, so it becomes a form-level error instead of vanishing.
For the sample response the result is a view model withfieldErrors.email= "Enter an email address like name@example.com.", no form-level error andretryablefalse (422 is not a retryable status). CallingtoViewModelon it with alogcallback gives{"fieldErrors":{"email":"Enter an email address like name@example.com."},"retryable":false}(undefined entries are dropped byJSON.stringify), and the log callback receives{"status":422,"code":"invalid_field","message":"Invalid email","orphans":[]}. The server's "Invalid email" never reaches the screen. - Form-level errors. Anything that is not about one input: 401 (session expired), 429 / 503 (service busy), a 5xx, or a 400/409/422 that carries no usable field errors. A 409 or 422 that does carry a field error (a taken email) shows only that field message, with no banner saying the failure was on the server's side. These render in one message region above the form.
- Translation. The catalog is keyed by locale, then by key. A missing key in the active locale falls back to English, and a missing key everywhere falls back to the generic string, so an unexpected new server code never shows a raw identifier.
Retryable and not retryable
"Retryable" here is a client policy: whether the UI offers "Try again" because repeating the same request can plausibly succeed.
| Failure | Offer retry? | Why |
|---|---|---|
| Network error (fetch rejected) | Yes | Nothing reached the server or no answer came back; the entered data is still in the form |
| 408, 502, 503, 504 | Yes | Timeout or upstream trouble, usually transient |
| 429 | Yes, after a wait | Rate limit. Retry-After is either a number of seconds or an HTTP date (MDN, Retry-After), and the code parses both |
| 400, 422 | No | The same input fails the same way; the user must edit a field |
| 401 | No | Retrying without signing in again fails; send the user to sign in |
| 409 | No | A conflict (such as a duplicate) needs a decision, not a repeat |
| 500 | No | Usually a deterministic server bug; show the generic message and a support reference |
The status classes in the table are exactly what the code below returns, and the test checks every row. Offering a button is different from retrying automatically. A form submit is a POST, and repeating a POST can create a duplicate record if the first request actually succeeded but the response was lost. Retry automatically only for GET requests, or for POSTs that carry a client-generated idempotency key (a unique token the server uses to recognise and ignore a repeated request). Otherwise let the user press the button.
Messages you do not want to show verbatim
Server message strings can leak internals ("pg pool exhausted at 10.0.3.7"), come in one language, change without notice, or contain text that was never reviewed. The rule is that only strings from your catalog reach the DOM. The raw code, message, status and request id (an identifier the server stamps on each response, here read from the X-Request-Id header) go to a log callback (telemetry: diagnostic data sent to a monitoring system), so support can match a user's report to a server log line. The test below asserts that both a raw validation message and a raw 503 message are absent from the page while the log still holds the first.
Working code
apiErrors.js is the mapping layer:
// Message catalogs: the ONLY text users see. Keys are `${field}.${code}` or a bare code.
export const CATALOG = {
en: {
'email.invalid_format': 'Enter an email address like name@example.com.',
'email.taken': 'That email is already registered. Try signing in.',
'password.too_short': 'Use at least 8 characters.',
required: 'This field is required.',
invalid_field: 'Check this field and try again.',
network: 'We could not reach the server. Check your connection and try again.',
busy: 'The service is busy. Try again in a moment.',
session: 'Your session expired. Sign in again.',
generic: 'Something went wrong on our side. Your entries are still here.',
},
es: {
'email.invalid_format': 'Introduce un correo como nombre@ejemplo.com.',
generic: 'Algo salio mal por nuestra parte. Tus datos siguen aqui.',
},
};
const RETRYABLE_STATUS = new Set([408, 429, 502, 503, 504]);
export function t(key, locale = 'en') {
return CATALOG[locale]?.[key] ?? CATALOG.en[key] ?? undefined;
}
// Retry-After is either delay-seconds or an HTTP-date (MDN / RFC 9110).
export function parseRetryAfter(value, now = Date.now()) {
if (value == null || value === '') return undefined;
if (/^\d+$/.test(value)) return Number(value) * 1000;
const at = Date.parse(value);
return Number.isNaN(at) ? undefined : Math.max(0, at - now);
}
// input: { networkError } or { status, body, retryAfter, requestId }
// returns a view model; err.message is never part of it.
export function toViewModel(input, knownFields, { locale = 'en', log = () => {}, now } = {}) {
if (input.networkError) {
return { fieldErrors: {}, formError: t('network', locale), retryable: true };
}
const err = input.body && typeof input.body === 'object' ? input.body.error : undefined;
const fields = err && typeof err.fields === 'object' && err.fields ? err.fields : {};
const fieldErrors = {};
const orphans = [];
for (const [name, code] of Object.entries(fields)) {
const text = t(`${name}.${code}`, locale) ?? t(String(code), locale) ?? t('invalid_field', locale);
if (knownFields.includes(name)) fieldErrors[name] = text;
else orphans.push(name); // server blames a field this form does not render
}
let formError;
if (input.status === 401) formError = t('session', locale);
else if (input.status === 429 || input.status === 503) formError = t('busy', locale);
else if (input.status === 400 || input.status === 409 || input.status === 422) {
if (Object.keys(fieldErrors).length === 0) formError = t('generic', locale);
} else formError = t('generic', locale);
if (orphans.length) formError = formError ?? t('generic', locale);
// The raw server text goes to telemetry only.
log({ status: input.status, code: err?.code, message: err?.message, orphans, requestId: input.requestId });
const retryable = RETRYABLE_STATUS.has(input.status);
return {
fieldErrors,
formError,
retryable,
retryAfterMs: retryable ? parseRetryAfter(input.retryAfter, now) : undefined,
};
}
// fetch wrapper: fetch rejects only on network failure, so HTTP errors are read from the Response.
export async function postJson(url, payload, fetchImpl = fetch) {
let res;
try {
res = await fetchImpl(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
} catch {
return { networkError: true };
}
if (res.ok) return { ok: true };
let body;
try { body = await res.json(); } catch { body = undefined; } // proxies return HTML 502s
return { status: res.status, body, retryAfter: res.headers.get('Retry-After'), requestId: res.headers.get('X-Request-Id') };
}
SignupForm.jsx renders the view model. It moves keyboard focus to the first invalid input after a failed submit, links each message to its input with aria-describedby and sets aria-invalid="true" only after validation has run (MDN says to set it as the result of validation, not in the initial markup). The form-level region is a role="alert" container that is always present in the markup and has its text filled in later, which is the pattern MDN gives for getting a live announcement (a container added together with its text is generally not announced). The submit button is disabled while a request is pending, so a double click cannot send two requests:
import React, { useEffect, useId, useRef, useState } from 'react';
import { postJson, toViewModel } from './apiErrors.js';
const FIELDS = ['email', 'password'];
export function SignupForm({ locale = 'en', log }) {
const uid = useId();
const refs = { email: useRef(null), password: useRef(null) };
const [values, setValues] = useState({ email: '', password: '' });
const [vm, setVm] = useState({ fieldErrors: {}, formError: '', retryable: false });
const [pending, setPending] = useState(false);
const [done, setDone] = useState(false);
const [errorRound, setErrorRound] = useState(0);
// After a failed submit, move focus to the first invalid field in DOM order.
useEffect(() => {
const first = FIELDS.find((f) => vm.fieldErrors[f]);
if (first) refs[first].current.focus();
}, [errorRound]); // eslint-disable-line react-hooks/exhaustive-deps
async function onSubmit(e) {
e.preventDefault();
if (pending) return; // double-submit guard
setPending(true);
const result = await postJson('/api/signup', values);
setPending(false);
if (result.ok) return setDone(true);
setVm(toViewModel(result, FIELDS, { locale, log }));
setErrorRound((n) => n + 1);
}
const change = (name) => (e) => {
setValues((v) => ({ ...v, [name]: e.target.value }));
setVm((p) => ({ ...p, fieldErrors: { ...p.fieldErrors, [name]: undefined } }));
};
if (done) return <p>Account created.</p>;
return (
<form onSubmit={onSubmit} noValidate>
<div role="alert">{vm.formError}</div>
{FIELDS.map((name) => {
const err = vm.fieldErrors[name];
return (
<div key={name}>
<label htmlFor={`${uid}-${name}`}>{name}</label>
<input id={`${uid}-${name}`} ref={refs[name]} value={values[name]} onChange={change(name)}
type={name === 'password' ? 'password' : 'text'}
aria-invalid={err ? 'true' : undefined}
aria-describedby={err ? `${uid}-${name}-err` : undefined} />
{err && <p id={`${uid}-${name}-err`}>{err}</p>}
</div>
);
})}
<button type="submit" disabled={pending}>{pending ? 'Saving...' : vm.retryable ? 'Try again' : 'Sign up'}</button>
</form>
);
}
test.jsx renders the form with React 18 and Testing Library under jsdom and mocks fetch:
import assert from 'node:assert/strict';
import React from 'react';
import { render, screen, cleanup, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { SignupForm } from './SignupForm.jsx';
import { toViewModel, parseRetryAfter } from './apiErrors.js';
const json = (status, body, headers = {}) =>
new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json', ...headers } });
const tests = [];
const test = (name, fn) => tests.push([name, fn]);
test('field error: translated text, aria wiring, focus, raw message hidden', async () => {
const logs = [];
globalThis.fetch = async () => json(422, { error: { code: 'invalid_field', message: 'Invalid email', fields: { email: 'invalid_format' } } });
render(<SignupForm log={(x) => logs.push(x)} />);
await userEvent.type(screen.getByLabelText('email'), 'nope');
await userEvent.click(screen.getByRole('button', { name: 'Sign up' }));
const input = await screen.findByLabelText('email');
const msg = await screen.findByText('Enter an email address like name@example.com.');
assert.equal(input.getAttribute('aria-invalid'), 'true');
assert.equal(input.getAttribute('aria-describedby'), msg.id);
assert.equal(document.activeElement, input);
assert.equal(screen.queryByText('Invalid email'), null);
assert.equal(logs[0].message, 'Invalid email'); // kept for telemetry only
assert.equal(screen.getByRole('alert').textContent, ''); // no form-level banner for pure field errors
});
test('503 + Retry-After: form-level message, retryable, button says Try again', async () => {
globalThis.fetch = async () => json(503, { error: { code: 'upstream', message: 'pg pool exhausted at 10.0.3.7' } }, { 'Retry-After': '30' });
render(<SignupForm />);
await userEvent.click(screen.getByRole('button', { name: 'Sign up' }));
await waitFor(() => assert.equal(screen.getByRole('alert').textContent, 'The service is busy. Try again in a moment.'));
assert.ok(screen.getByRole('button', { name: 'Try again' }));
assert.ok(!document.body.textContent.includes('pg pool'));
});
test('network failure keeps entries and is retryable; HTML 502 body does not crash', async () => {
let calls = 0;
globalThis.fetch = async () => { calls++; if (calls === 1) throw new TypeError('Failed to fetch'); return new Response('<html>Bad Gateway</html>', { status: 502 }); };
render(<SignupForm />);
await userEvent.type(screen.getByLabelText('email'), 'a@b.co');
await userEvent.click(screen.getByRole('button', { name: 'Sign up' }));
await waitFor(() => assert.match(screen.getByRole('alert').textContent, /could not reach the server/));
assert.equal(screen.getByLabelText('email').value, 'a@b.co');
await userEvent.click(screen.getByRole('button', { name: 'Try again' }));
await waitFor(() => assert.match(screen.getByRole('alert').textContent, /went wrong on our side/));
assert.equal(calls, 2);
});
test('pure mapping: unknown code, unknown field, locale fallback, retry classes, Retry-After', () => {
const known = ['email', 'password'];
const a = toViewModel({ status: 422, body: { error: { code: 'invalid_field', fields: { email: 'brand_new_code', zip: 'required' } } } }, known);
assert.equal(a.fieldErrors.email, 'Check this field and try again.');
assert.equal(a.formError, 'Something went wrong on our side. Your entries are still here.'); // zip is not rendered
assert.equal(toViewModel({ status: 422, body: { error: { fields: { email: 'invalid_format' } } } }, known, { locale: 'es' }).fieldErrors.email, 'Introduce un correo como nombre@ejemplo.com.');
const dup = toViewModel({ status: 409, body: { error: { code: 'conflict', fields: { email: 'taken' } } } }, known);
assert.equal(dup.fieldErrors.email, 'That email is already registered. Try signing in.');
assert.equal(dup.formError, undefined); // a duplicate is the user's to fix: no 'our side' banner on top of the field message
assert.equal(toViewModel({ status: 422, body: { error: { fields: { password: 'too_short' } } } }, known, { locale: 'es' }).fieldErrors.password, 'Use at least 8 characters.'); // falls back to en
const retry = Object.fromEntries([400, 401, 409, 422, 500, 408, 429, 502, 503, 504].map((s) => [s, toViewModel({ status: s }, known).retryable]));
assert.deepEqual(retry, { 400: false, 401: false, 409: false, 422: false, 500: false, 408: true, 429: true, 502: true, 503: true, 504: true });
assert.equal(parseRetryAfter('120'), 120000);
assert.equal(parseRetryAfter('Wed, 21 Oct 2015 07:28:00 GMT', Date.parse('Wed, 21 Oct 2015 07:27:00 GMT')), 60000);
assert.equal(parseRetryAfter('soon'), undefined);
assert.equal(toViewModel({ status: 429, retryAfter: '5' }, known).retryAfterMs, 5000);
});
let failed = 0;
for (const [name, fn] of tests) {
try { await fn(); console.log('PASS', name); } catch (e) { failed++; console.log('FAIL', name, '\n ', e.message.split('\n')[0]); }
cleanup();
}
console.log(failed ? `${failed} failed` : 'all passed');
process.exit(failed ? 1 : 0);
Trade-offs and pitfalls
- Codes beat messages as the contract. If the API only sends English
messagetext, the client cannot translate or branch on it. Ask for stable codes; where a field has no mapped code, the generic fallback keeps the UI honest. - Clear a field's error when the user edits that field, as
changedoes, so a stale message does not outlive the input it described. Keep every entry in the form on failure; wiping the form on an error is the commonest way to lose a user. - Do not set
aria-invalidon pristine fields. MDN advises against flagging empty required fields before the user has tried to submit. - Do not announce twice. Field errors are reached through focus plus
aria-describedby; therole="alert"region is for form-level text only, so a screen reader is not told the same failure by two channels. - Do not show
Retry-Afteras a raw number to users. Disable the button forretryAfterMs, or word it as "try again in a moment". - Server-side checks stay the authority. Client validation is a convenience; the mapping above exists because the server can still reject input the client accepted (a taken email, a changed rule).
Running the code
Save the files under src/ as apiErrors.js, SignupForm.jsx, test.jsx, setup.mjs and run.sh (the last two are scaffolding for running the test in Node, not part of the feature: setup.mjs installs jsdom globals, a simulated browser DOM, and run.sh bundles the JSX with esbuild and runs it):
import { JSDOM } from 'jsdom';
const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/' });
globalThis.window = dom.window;
globalThis.document = dom.window.document;
Object.defineProperty(globalThis, 'navigator', { value: dom.window.navigator, configurable: true });
globalThis.HTMLElement = dom.window.HTMLElement;
cd /w && mkdir -p out && npx esbuild src/test.jsx --bundle --platform=node --format=esm --packages=external --loader:.js=jsx --outfile=out/t.mjs --log-level=error && node --import ./src/setup.mjs out/t.mjs 2>&1 | grep -E '^(PASS|FAIL|all passed|[0-9]+ failed)'
Run in a node:22 container (Node 22, React 18.3.1, jsdom 30), after npm i react@18 react-dom@18 @testing-library/react@14 @testing-library/user-event@14 jsdom esbuild in the mounted folder, with docker run --rm --ulimit core=0 -v "$PWD":/w -v "$PWD/src":/w/src:ro node:22 sh /w/src/run.sh, it prints:
PASS field error: translated text, aria wiring, focus, raw message hidden
PASS 503 + Retry-After: form-level message, retryable, button says Try again
PASS network failure keeps entries and is retryable; HTML 502 body does not crash
PASS pure mapping: unknown code, unknown field, locale fallback, retry classes, Retry-After
all passed
The harness can fail: with the aria-describedby attribute and the focus call deleted from SignupForm.jsx, the first test prints FAIL and the run ends with 1 failed.
Explain the difference between controlled and uncontrolled form inputs in React: how each affects event handling, keeping state in sync and performance. Convert an input that uses a ref into a controlled one, and say when you would pick each approach.
Sample Answer
Direct answer
A controlled input is one whose current value is owned by React state: you pass value and an onChange handler, and React forces the input to always show what the state says. An uncontrolled input keeps its value in the browser's DOM; you give it at most a starting value with defaultValue, and read the current value when you need it (through a ref, or FormData on submit). Controlled gives you the value on every keystroke, which is what live validation, formatting, dependent fields and "disable the button until valid" need, at the cost of a re-render per keystroke. Uncontrolled is less code and renders nothing while typing, which suits simple forms that only need the values at submit. Pick controlled when the UI must react to the value as it changes, uncontrolled when it only needs it once.
How each one works
Event handling. Controlled: every change fires onChange, you call the state setter, React re-renders and writes the new value into the DOM input. If you pass value and no onChange, the field becomes read-only and React logs a warning; React's own docs call this out (use defaultValue, onChange, or readOnly). Uncontrolled: the browser edits its own copy; your code does nothing during typing and reads inputRef.current.value (or a FormData) at the moment it needs it.
Keeping state in sync. A controlled input has one source of truth (the single place that holds the authoritative value; here the React state), so a "Reset" button, a value loaded from the server or a formatter (strip non-digits) is just a state update. For an uncontrolled input the DOM is the source of truth; resetting means calling form.reset() or setting ref.current.value imperatively (by issuing a direct command to the DOM node instead of describing the value through state), and there is no state to render from.
Performance. Controlled re-renders the component (and its children, unless they are memoized, i.e. wrapped with React.memo so React skips re-rendering them when their props did not change) on each keystroke. Uncontrolled does not. The proof test under "Proof" below counts renders deterministically rather than timing them. Its console output is reproduced here; the two warning lines are deliberately cut to their first 110 to 118 characters by the test's slice so they fit on one line:
renders after typing 5 characters: { uncontrolled: 1, controlled: 6 }
saved: [["uncontrolled","Adahello"],["controlled","Adahello"]]
FormData result: {"first":"Ada","last":"Lovelace","subscribe":"on"}
warning: Warning: A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing f
stuck warning: Warning: You provided a `value` prop to a form field without an `onChange` handler. This will render a read-on
Typing 5 characters costs 5 extra renders when controlled and none when uncontrolled. For a small form this is invisible; it matters when the form has many fields or expensive children, in which case keep state local to each field component, memoize the heavy children, or make the rarely-needed fields uncontrolled.
Converting a ref input to a controlled one
Steps: replace the useRef with useState seeded with the old defaultValue; pass value={name}; add onChange={(e) => setName(e.target.value)}; read the state (not the ref) on submit. The two components below are the same form before and after (components 1 and 2 in the code).
import { useEffect, useRef, useState } from 'react';
// 1. Uncontrolled: the DOM owns the value; React reads it through a ref when it needs it.
export function UncontrolledName({ onSave, counter }) {
counter.renders += 1;
const inputRef = useRef(null);
return (
<form onSubmit={(e) => { e.preventDefault(); onSave(inputRef.current.value); }}>
<label htmlFor="n1">Name</label>
<input id="n1" ref={inputRef} defaultValue="Ada" />
<button>Save</button>
</form>
);
}
// 2. The same form converted to controlled: React state owns the value, the input only displays it.
export function ControlledName({ onSave, counter }) {
counter.renders += 1;
const [name, setName] = useState('Ada');
return (
<form onSubmit={(e) => { e.preventDefault(); onSave(name); }}>
<label htmlFor="n2">Name</label>
<input id="n2" value={name} onChange={(e) => setName(e.target.value)} />
<button>Save</button>
</form>
);
}
// 3. Uncontrolled with several fields: read everything at once with FormData (every input needs a name).
export function FormDataForm({ onSave }) {
return (
<form onSubmit={(e) => { e.preventDefault(); onSave(Object.fromEntries(new FormData(e.currentTarget))); }}>
<label htmlFor="fn">First</label><input id="fn" name="first" defaultValue="Ada" />
<label htmlFor="ln">Last</label><input id="ln" name="last" defaultValue="Lovelace" />
<label htmlFor="ok">Subscribe</label><input id="ok" name="subscribe" type="checkbox" />
<button>Save</button>
</form>
);
}
// 4. A controlled input whose value arrives later: undefined first, then a string.
export function LoadedName({ loadName, initial }) {
const [name, setName] = useState(initial); // undefined: React treats the input as uncontrolled
useEffect(() => { loadName().then(setName); }, [loadName]);
return <input aria-label="Loaded name" value={name} onChange={(e) => setName(e.target.value)} />;
}
// 5. value without onChange: React makes the field read-only and warns.
export function StuckInput() {
return <input aria-label="Stuck" value="fixed" />;
}
Proof, rendered with React 18 and Testing Library under jsdom:
import { describe, it, expect, vi, afterEach } from 'vitest';
import { render, screen, cleanup, act } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { UncontrolledName, ControlledName, FormDataForm, LoadedName, StuckInput } from './forms.jsx';
afterEach(cleanup);
describe('controlled vs uncontrolled', () => {
it('renders once per keystroke when controlled, and not at all after mount when uncontrolled', async () => {
const user = userEvent.setup();
const a = { renders: 0 }; const b = { renders: 0 };
const saved = [];
const { unmount } = render(<UncontrolledName counter={a} onSave={(v) => saved.push(['uncontrolled', v])} />);
await user.type(screen.getByLabelText('Name'), 'hello');
await user.click(screen.getByRole('button'));
unmount();
render(<ControlledName counter={b} onSave={(v) => saved.push(['controlled', v])} />);
await user.type(screen.getByLabelText('Name'), 'hello');
await user.click(screen.getByRole('button'));
console.log('renders after typing 5 characters:', { uncontrolled: a.renders, controlled: b.renders });
console.log('saved:', JSON.stringify(saved));
expect(a.renders).toBe(1);
expect(b.renders).toBe(6); // 1 mount + 5 keystrokes
expect(saved).toEqual([['uncontrolled', 'Adahello'], ['controlled', 'Adahello']]);
});
it('reads several uncontrolled fields at once with FormData', async () => {
const user = userEvent.setup();
let got;
render(<FormDataForm onSave={(v) => (got = v)} />);
await user.click(screen.getByLabelText('Subscribe'));
await user.click(screen.getByRole('button'));
console.log('FormData result:', JSON.stringify(got));
expect(got).toEqual({ first: 'Ada', last: 'Lovelace', subscribe: 'on' });
});
it('does not warn when the value starts as an empty string, and warns when it starts as undefined', async () => {
const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
const loadName = () => Promise.resolve('Ada');
// The fixed version goes first: React reports this particular warning only once per page load.
await act(async () => { render(<LoadedName loadName={loadName} initial="" />); });
expect(spy).not.toHaveBeenCalled();
expect(screen.getByLabelText('Loaded name').value).toBe('Ada');
cleanup();
await act(async () => { render(<LoadedName loadName={loadName} initial={undefined} />); });
const warning = spy.mock.calls.map((c) => String(c[0])).find((m) => m.includes('changing an uncontrolled input to be controlled'));
console.log('warning:', warning.split('\n')[0].slice(0, 118));
expect(warning).toBeTruthy();
expect(screen.getByLabelText('Loaded name').value).toBe('Ada');
spy.mockRestore();
});
it('value without onChange makes the input read-only and React says so', async () => {
const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
const user = userEvent.setup();
render(<StuckInput />);
await user.type(screen.getByLabelText('Stuck'), 'abc');
expect(screen.getByLabelText('Stuck').value).toBe('fixed');
const msg = spy.mock.calls.map((c) => String(c[0])).find((m) => m.includes('without an `onChange` handler'));
console.log('stuck warning:', msg.slice(0, 110));
expect(msg).toBeTruthy();
spy.mockRestore();
});
});
Switch warning and FormData
- Uncontrolled to controlled warning. React treats an input as controlled when it receives a string
valueand as uncontrolled whenvalueisundefined; an input cannot change from one to the other during its lifetime. The common cause is state that startsundefined(data not loaded yet) and later becomes a string, which logs "A component is changing an uncontrolled input to be controlled". The fix, shown byLoadedNamewithinitial="", is to keep the value a string from the first render (useState(user?.name ?? '')). React's documentation gives the same fallback pattern (value={someValue ?? ''}). - FormData. For an uncontrolled form,
new FormData(e.currentTarget)reads every named field at once; every input needs aname, andObject.fromEntriesturns it into an object. A checked checkbox with novalueattribute comes through as'on', as the output above shows (subscribe: "on").
Advantages of controlled components
- Instant validation and formatting as the user types, because the value is available in each render.
- Conditional UI from the value: enable or disable a button, show a character count, reveal a dependent field.
- One source of truth, so programmatic changes (reset, prefill, "copy billing address") are plain state updates.
- Easy to test and to keep in sync with other state (URL, a store, a server draft).
- The component fully decides what the input may contain, for example rejecting characters by not storing them.
Trade-offs
- Choose controlled for live validation, masks, dependent fields and anything the UI shows from the value; choose uncontrolled for a plain submit-only form, or a large form where per-keystroke renders matter.
- Pitfalls:
valuewithoutonChange;value={undefined}ornullat first; passing bothvalueanddefaultValue(React's docs: an input cannot be both controlled and uncontrolled); storing derived values in state instead of computing them.
Running the code
Save the first code block above as forms.jsx, the second as controlled.test.jsx, and put this vitest.config.mjs beside them (the files use JSX without importing React and the tests need a DOM, so without it they fail with a missing document):
import { defineConfig } from 'vitest/config';
export default defineConfig({ esbuild: { jsx: 'automatic' }, test: { environment: 'jsdom' } });
npm i react@18 react-dom@18 @testing-library/react@14 @testing-library/user-event@14 jsdom vitest@2.1.8
npx vitest run controlled
Run in a node:22 container (React 18.3.1, jsdom 30), this prints 4 passing tests and the lines logged above. Both forms save the same value, Adahello, after typing "hello" onto the starting value "Ada".
Implement a custom select control in React: a button that opens a list of options, with the open state exposed to assistive technology, selection by keyboard, closing on Escape, and options announced by a screen reader. Show the key parts of the component.
Sample Answer
Direct answer
Build it as the WAI-ARIA Authoring Practices (APG) "select-only combobox": a button with role="combobox" as the trigger and a role="listbox" of role="option" items as the popup. The trigger exposes the open state through aria-expanded, names the popup type with aria-haspopup="listbox", and links to the list with aria-controls. DOM focus never leaves the trigger; the highlighted option is communicated through aria-activedescendant, which is what makes a screen reader announce each option as the arrow keys move. Enter or Space commits the highlighted option, Escape closes without changing the value, and focus stays on the trigger in both cases. If a native <select> meets the design, use that instead: it already does all of this, including the mobile pickers.
Plain words for the roles: the accessibility tree is the structure the browser hands to screen readers (roles, names and states of elements), which can differ from the visual page. A popup is the panel that appears over the page when the control opens. A listbox is a list of choices from which one is picked, and each choice is an option. A combobox is a control that shows a current value and opens such a list; the "select-only" kind does not allow typing free text, which is why a plain button can play the role. aria-activedescendant names which option is highlighted while real focus stays on the trigger.
Why this pattern
APG's older "collapsible dropdown listbox" example (a button that moves focus into the list) is marked deprecated, and APG recommends the select-only combobox instead. In that pattern the combobox is the thing with focus; the listbox is a popup it controls. combobox is a permitted role on a <button> element (ARIA in HTML), so the trigger stays a real button. A <button> also means Enter and Space already activate it and it is in the tab order without extra work.
The component
import { useId, useRef, useState } from 'react';
export function Select({ label, name, options, defaultValue = options[0] }) {
const uid = useId();
const [value, setValue] = useState(defaultValue);
const [open, setOpen] = useState(false);
const [active, setActive] = useState(options.indexOf(defaultValue));
const typed = useRef({ text: '', at: 0 });
const optionId = (i) => `${uid}-opt-${i}`;
function openAt(i) { setActive(i); setOpen(true); }
function commit(i) { setValue(options[i]); setOpen(false); }
const clamp = (i) => Math.max(0, Math.min(options.length - 1, i));
function onKeyDown(e) {
if (e.altKey && e.key === 'ArrowDown' && !open) { e.preventDefault(); return openAt(options.indexOf(value)); }
if (e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey && e.key !== ' ') {
// type-ahead: characters typed within 500 ms accumulate; the first option starting with them is highlighted
const now = Date.now();
typed.current = { text: (now - typed.current.at > 500 ? '' : typed.current.text) + e.key.toLowerCase(), at: now };
const hit = options.findIndex((o) => o.toLowerCase().startsWith(typed.current.text));
if (hit >= 0) openAt(hit);
return;
}
if (!open) {
if (['ArrowDown', 'Enter', ' '].includes(e.key)) { e.preventDefault(); openAt(options.indexOf(value)); }
else if (e.key === 'ArrowUp' || e.key === 'Home') { e.preventDefault(); openAt(0); }
else if (e.key === 'End') { e.preventDefault(); openAt(options.length - 1); }
return;
}
switch (e.key) {
case 'ArrowDown': e.preventDefault(); setActive(clamp(active + 1)); break;
case 'ArrowUp': e.preventDefault(); setActive(clamp(active - 1)); break;
case 'Home': e.preventDefault(); setActive(0); break;
case 'End': e.preventDefault(); setActive(options.length - 1); break;
case 'Enter': case ' ': e.preventDefault(); commit(active); break;
case 'Escape': e.preventDefault(); setOpen(false); break; // value unchanged, focus never left the combobox
case 'Tab': commit(active); break; // let Tab move focus on
}
}
return (
<div>
<span id={`${uid}-label`}>{label}</span>
<button
type="button"
id={`${uid}-combo`}
role="combobox"
aria-haspopup="listbox"
aria-expanded={open}
aria-controls={`${uid}-list`}
aria-labelledby={`${uid}-label`}
aria-activedescendant={open ? optionId(active) : undefined}
onClick={(e) => {
e.currentTarget.focus(); // Safari does not focus a button on click; keys and blur need the trigger focused
if (open) setOpen(false);
else openAt(options.indexOf(value));
}}
onKeyDown={onKeyDown}
onBlur={() => open && commit(active)}
>
{value}
</button>
<input type="hidden" name={name} value={value} />
<ul id={`${uid}-list`} role="listbox" aria-labelledby={`${uid}-label`} hidden={!open}
onMouseDown={(e) => e.preventDefault() /* keep DOM focus on the combobox */}>
{options.map((o, i) => (
<li key={o} id={optionId(i)} role="option" aria-selected={open && i === active}
onClick={() => commit(i)} onMouseMove={() => setActive(i)}>
{o}
</li>
))}
</ul>
</div>
);
}
Key parts and why they are there. Two small traces make the arithmetic concrete. Clamping: with four options (indexes 0 to 3) and Date highlighted (3), ArrowDown computes clamp(4) = Math.max(0, Math.min(3, 4)) = 3, so it stops at the end; ArrowUp on Apple computes clamp(-1) = 0. Type-ahead with options Apple, Banana, Cherry, Date: typing c makes the buffer 'c', and the first option starting with it is Cherry (index 2); typing h within 500 ms makes the buffer 'ch', still Cherry; typing d after a pause longer than 500 ms resets the buffer to 'd' and highlights Date.
- Open state exposed:
aria-expanded={open}renders as"true"or"false"; the list also getshiddenwhile closed, which removes it from the accessibility tree. - Options announced: each option has
role="option"and anid. While open,aria-activedescendanton the trigger points at the highlighted option's id. Moving the highlight changes that attribute only, so the screen reader reads the new option without DOM focus moving. APG setsaria-selected="true"on the highlighted option while it is referenced byaria-activedescendant; the code does the same. - Keyboard (as APG specifies): closed: Down, Enter and Space open it; Up and Home open at the first option; End opens at the last. Open: Up and Down move (and stop at the ends), Home and End jump, Enter or Space commit and close, Escape closes with no change, Tab commits and lets focus move on. Printable characters jump to the first option starting with what was typed within 500 ms (type-ahead).
- Focus after closing: Enter, Space and Escape all leave DOM focus on the trigger, because it never moved off it. Opening with the keyboard needs no
focus()call. Opening with the mouse does: MDN notes that Safari does not focus a button when it is clicked, so without the explicitfocus()in the click handler a mouse-opened list in Safari would have no focused trigger, Escape and the arrow keys would do nothing, and clicking elsewhere would never blur it, leaving the list open. Callingfocus()on a button that already has focus is harmless. - Mouse:
onMouseDownwithpreventDefault()on the list stops the click from blurring the trigger, so clicking an option does not trigger the blur-commit first (without it, pressing the mouse button on an option moves focus off the trigger, the blur handler commits whichever option is currently highlighted and closes the list, and the click may never reach the option that was pressed; in Playwright 1.48.2, clicking Cherry without thepreventDefaultusually left the value at Apple in Chromium and WebKit (an occasional run picked Cherry) and picked Cherry every time in Firefox, so the outcome depends on the engine and on timing); a click outside blurs the trigger, which commits the highlighted option and closes (APG: the value is committed when focus leaves the combobox). - Form value: a hidden
<input name>carries the chosen value into a normal form submit.
For long lists, APG notes that browsers do not scroll the aria-activedescendant target into view automatically, so a real implementation scrolls the highlighted option into view when it changes.
Menu versus listbox semantics
The takeaway: a value picker is a listbox, a list of commands is a menu. A select is "pick one value", so it is a listbox. A dropdown of commands (Edit, Duplicate, Delete) is a different widget with a different role set:
| Select (value) | Menu button (actions) | |
|---|---|---|
| Trigger | role="combobox" with aria-haspopup="listbox" | A button with aria-haspopup="menu" (or true) |
| Popup | role="listbox" with role="option" children | role="menu" with menuitem, menuitemcheckbox or menuitemradio children |
| Focus while open | Stays on the trigger; aria-activedescendant marks the highlighted option | Moves to the first menu item (the menu button pattern: Enter, Space or Down) |
| Selecting | Changes the field's value | Runs a command; the menu closes |
| Escape | Closes, value unchanged | Closes and returns focus to the element that opened it |
| Tab | Commits the highlighted option, closes and moves on | Leaves the menu and closes it |
APG describes a menu as a list of choices "such as a set of actions or functions", resembling an operating system menu, which is why a value picker should not use role="menu": its items are commands, focus moves into them rather than staying on the trigger, and Tab leaves and closes the menu instead of committing a choice. Using menu roles for a value picker, or option roles for a command list, is the common mix-up. A dropdown of links is a third case, and a button that toggles a plain list of links is usually simpler than either widget.
Proof
The tests render the component with React 18 and Testing Library under jsdom (save the component as Select.jsx and the tests as selectbox.test.jsx). They check the name, collapsed state and popup type; Enter opening with DOM focus left on the trigger and aria-activedescendant set; arrows moving the highlight without changing the value until Enter commits it; Escape closing without a change; Home, End and type-ahead; and mouse selection plus Tab commit.
import { describe, it, expect, afterEach } from 'vitest';
import { render, screen, cleanup } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Select } from './Select.jsx';
afterEach(cleanup);
const fruits = ['Apple', 'Banana', 'Cherry', 'Date'];
const setup = () => {
const user = userEvent.setup();
const { container } = render(<Select label="Favorite fruit" name="fruit" options={fruits} />);
const combo = screen.getByRole('combobox');
const hidden = () => container.querySelector('input[name="fruit"]').value;
const activeText = () => document.getElementById(combo.getAttribute('aria-activedescendant'))?.textContent;
return { user, combo, hidden, activeText };
};
describe('custom select', () => {
it('exposes name, collapsed state and popup type', () => {
const { combo } = setup();
expect(combo.getAttribute('aria-expanded')).toBe('false');
expect(combo.getAttribute('aria-haspopup')).toBe('listbox');
expect(screen.getByRole('combobox', { name: 'Favorite fruit' })).toBe(combo);
expect(screen.queryByRole('listbox')).toBeNull(); // hidden list is out of the accessibility tree
});
it('opens with Enter, keeps DOM focus on the combobox, and points aria-activedescendant at the current option', async () => {
const { user, combo, activeText } = setup();
combo.focus();
await user.keyboard('{Enter}');
expect(combo.getAttribute('aria-expanded')).toBe('true');
expect(screen.getAllByRole('option').map((o) => o.textContent)).toEqual(fruits);
expect(document.activeElement).toBe(combo);
expect(activeText()).toBe('Apple');
});
it('moves the highlight with arrows without changing the value until Enter commits it', async () => {
const { user, combo, hidden, activeText } = setup();
combo.focus();
await user.keyboard('{ArrowDown}{ArrowDown}'); // the first press opens at Apple, the second moves to Banana
expect(activeText()).toBe('Banana');
await user.keyboard('{ArrowDown}');
expect(activeText()).toBe('Cherry');
expect(hidden()).toBe('Apple');
expect(screen.getByRole('option', { name: 'Cherry' }).getAttribute('aria-selected')).toBe('true');
await user.keyboard('{Enter}');
expect(hidden()).toBe('Cherry');
expect(combo.textContent).toBe('Cherry');
expect(combo.getAttribute('aria-expanded')).toBe('false');
expect(document.activeElement).toBe(combo);
});
it('Escape closes without changing the value and focus stays on the trigger', async () => {
const { user, combo, hidden } = setup();
combo.focus();
await user.keyboard('{ArrowDown}{ArrowDown}{Escape}');
expect(combo.getAttribute('aria-expanded')).toBe('false');
expect(hidden()).toBe('Apple');
expect(document.activeElement).toBe(combo);
});
it('supports Home, End and type-ahead', async () => {
const { user, combo, activeText } = setup();
combo.focus();
await user.keyboard('{End}');
expect(activeText()).toBe('Date');
await user.keyboard('{Home}');
expect(activeText()).toBe('Apple');
await user.keyboard('c');
expect(activeText()).toBe('Cherry');
});
it('selects with the mouse and commits on Tab', async () => {
const { user, combo, hidden } = setup();
await user.click(combo);
await user.click(screen.getByRole('option', { name: 'Banana' }));
expect(hidden()).toBe('Banana');
expect(document.activeElement).toBe(combo);
await user.keyboard('{ArrowDown}{ArrowDown}{Tab}'); // open at Banana, highlight Cherry, Tab commits it
expect(hidden()).toBe('Cherry');
});
});
Run with npx vitest run selectbox, it prints 6 passing tests (Tests 6 passed (6)). Changing Escape to commit the highlight makes the Escape test fail. These tests prove the attributes and key handling; what a particular screen reader says on each key press has to be checked by hand with NVDA, JAWS and VoiceOver, which an automated run cannot do.
Trade-offs and pitfalls
- Custom versus native: native
<select>wins on accessibility, mobile pickers and effort; build custom only for content a<select>cannot hold (icons, descriptions, grouped rich rows), and then budget for testing with real assistive technology. - Pitfalls: moving real focus into each option and losing the trigger;
aria-expandedleft"true"after close; closing on blur without committing (or committing without telling anyone);role="menu"on a value picker; a list rendered withdisplay: nonetoggled but not synced witharia-expanded; forgettingaria-controlson a popup that is portalled (rendered by React into a different place in the document, such as the end of<body>, to escape clipping) elsewhere in the DOM.
Running the code
Tested in a node:22 container.
npm i react@18.3.1 react-dom@18.3.1 jsdom vitest@2.1.8 @testing-library/react@16 @testing-library/dom @testing-library/user-event
npx vitest run selectbox
vitest.config.js, next to the files: export default { esbuild: { jsx: 'automatic' }, test: { environment: 'jsdom' } }. It lets the JSX compile without a React import and provides document. Without it all the tests fail: those that call userEvent.setup() stop with a TypeError about the missing document, and the rest with ReferenceError: React is not defined.
You are implementing validation for a long signup form. When should each field validate (while typing, on blur, on submit), how and where do you show inline errors versus a summary at the top, and where should focus go after a failed submit? Give the rules you would implement and the trade-offs.
Sample Answer
Direct answer
The rules I would implement: validate a field the first time the user leaves it (blur), never while they are still typing in it for the first time; once a field is showing an error, re-validate on every keystroke so the message disappears the moment the value is fixed; on submit, validate everything at once. Show each error inline, directly under its field, and also list all of them in a summary at the top of the form. After a failed submit, move keyboard focus to the summary (long form) so a screen reader user hears that something is wrong and can jump to each field from a link; on a short form with one to three fields, focus the first invalid field instead. Errors are exposed to assistive technology (AT, such as screen readers) through aria-invalid and aria-describedby, and the summary through a live region (an element whose changed text a screen reader speaks without focus moving; "assertive" regions interrupt what is being read, "polite" ones wait for a pause). "Blur" is the event a field fires when it loses focus, for example when the user tabs or clicks away.
Timing rules, field by field
| Moment | Rule | Why |
|---|---|---|
| While typing in a field never left | No error | An email is "invalid" until the last character is typed. Early errors read as the form scolding the user. |
| First blur | Validate and show the error | The user has signalled "I'm done with this". |
| Typing in a field already showing an error | Re-validate each keystroke | Immediate reward: the error clears as soon as it is fixed, with no need to blur again. |
| Cross-field rule (confirm password) | Recompute whenever either field changes, but only show it once the dependent field has been touched | Editing the password can fix or break the confirmation. |
| Submit | Validate all fields, mark all touched, show everything | Catches fields the user never visited. |
| Blur caused by pressing the submit button | Show nothing; let the submit handler validate everything | An error line that appears on blur pushes the button down between mouse-down and mouse-up, and the click is lost |
| Server-only rule (email already registered) | Check on blur or on submit, with a pending state; never per keystroke | Each check costs a request, and half-typed values give meaningless answers. |
Native browser validation (required, type="email") is switched off with noValidate on the <form> so the app controls message wording, placement and focus. Browser bubbles vary by browser and cannot be styled (MDN). The constraint attributes can still stay on the inputs for semantics; the server validates again regardless.
Inline errors versus a summary
Use both. The inline message sits next to the field, so users see what to change where they are looking; the summary (a heading "There is a problem" plus one link per error, in the order the fields appear) gives a keyboard or screen reader user a single place to read all problems and jump to each one. The GOV.UK Design System makes this the rule: always show a summary at the top of the page, and also an inline message beside each answer, because the summary alone is not enough. Each summary link focuses its field (in the code, inputs.current[k].focus()), and the link text is the same message as the inline one.
Where focus goes after a failed submit
| Form | Focus target | Reason |
|---|---|---|
| Long form (more than three fields) | The error summary container (tabIndex=-1, focusable by script but not in the tab order) | Fields may be off-screen; the user hears the summary heading and the list first, then follows a link. |
| Short form (1-3 fields) | The first invalid field | The summary adds little; the field's error is read through its description. |
Focus must be moved after the summary exists in the DOM, which is why the code sets it in an effect that runs after the render following the submit, and why attempt is a counter: a second failed submit with the same errors must still move focus back to the summary. Sequence: the first failed click takes attempt from 0 to 1, the summary mounts and the effect focuses it; the user then follows a link to the email field, so focus has left the summary; the second failed click changes no errors and the summary is already mounted, so a boolean flag would not change and the effect would not run, but the counter goes from 1 to 2, the effect re-runs and focus returns to the summary.
Announcing errors to screen readers
aria-invalid="true"on the input marks it as holding an invalid value. MDN advises not setting it on a field before the user has had a chance to fill it in (for example, an empty required field before the first submit); the code sets it only after blur or a submit attempt.aria-describedbypointing at the inline message makes a screen reader read the error as part of the field's description when the field receives focus. The message carries a visually hidden "Error: " prefix, so the meaning does not depend on colour. Thevisually-hiddenclass is not built in; it needs this CSS, which keeps the text in the page for screen readers while taking it out of the visual layout (in Chromium the span measures 1 px by 1 px and its text stays in the element's text):
.visually-hidden {
position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0;
overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0;
}
Without the class the prefix simply shows as visible text.
- The summary list lives in an element with
role="alert"(an assertive live region), nested inside the container that receives focus. GOV.UK movedrole="alert"to an inner element because putting it on the root caused JAWS not to read the whole summary. MDN saysalertmust be used sparingly and that an alert inserted already populated into the DOM generally does not announce reliably; here, focusing the container is the dependable path and the live region is the backup. - Do not make each inline message an alert. That would announce every blur error and again at submit, and several alerts at once give a bad experience (MDN).
Submit-time versus live validation, from an accessibility view: submit-time errors are predictable (one summary, one focus move), while live errors that interrupt typing are noisy for screen reader users and for people with motor or cognitive disabilities. The blur-then-live-correction hybrid above gives immediate feedback without interrupting the first pass through a field.
Code and tests
import { useEffect, useRef, useState } from 'react';
const rules = {
name: (v) => (v.trim() ? null : 'Enter your full name'),
email: (v) => (!v.trim() ? 'Enter your email address' : /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v) ? null : 'Enter an email address like name@example.com'),
password: (v) => (v.length >= 8 ? null : 'Password must be at least 8 characters'),
confirm: (v, all) => (!v ? 'Confirm your password' : v === all.password ? null : 'Passwords do not match'),
};
const labels = { name: 'Full name', email: 'Email', password: 'Password', confirm: 'Confirm password' };
const order = ['name', 'email', 'password', 'confirm'];
export function SignupValidation({ save }) {
const [values, setValues] = useState({ name: '', email: '', password: '', confirm: '' });
const [touched, setTouched] = useState({});
const [submitted, setSubmitted] = useState(false);
const summaryRef = useRef(null);
const pressingSubmit = useRef(false); // true while a pointer is held down on the submit button
const inputs = useRef({});
const errors = Object.fromEntries(order.map((k) => [k, rules[k](values[k], values)]));
// A field shows its error after it has been left once (blur) or after a submit attempt.
// While showing, it re-validates on every keystroke, so the message clears the moment it is fixed.
const shown = (k) => (touched[k] || submitted) && errors[k];
const summary = order.filter((k) => submitted && errors[k]);
const [attempt, setAttempt] = useState(0);
useEffect(() => {
if (attempt && summaryRef.current) summaryRef.current.focus(); // after the summary is in the DOM
}, [attempt]);
function onSubmit(e) {
e.preventDefault();
setSubmitted(true);
if (order.some((k) => errors[k])) {
setAttempt((n) => n + 1);
return;
}
save(values);
}
return (
<form onSubmit={onSubmit} noValidate>
{summary.length > 0 && (
<div ref={summaryRef} tabIndex={-1}>
<div role="alert">
<h2>There is a problem</h2>
<ul>
{summary.map((k) => (
<li key={k}>
<a href={`#${k}`} onClick={(e) => { e.preventDefault(); inputs.current[k].focus(); }}>{errors[k]}</a>
</li>
))}
</ul>
</div>
</div>
)}
{order.map((k) => (
<div key={k}>
<label htmlFor={k}>{labels[k]}</label>
<input
id={k}
ref={(el) => (inputs.current[k] = el)}
type={k === 'password' || k === 'confirm' ? 'password' : k === 'email' ? 'email' : 'text'}
value={values[k]}
aria-invalid={shown(k) ? 'true' : undefined}
aria-describedby={shown(k) ? `${k}-error` : undefined}
onChange={(e) => setValues({ ...values, [k]: e.target.value })}
onBlur={() => { if (!pressingSubmit.current) setTouched({ ...touched, [k]: true }); }}
/>
{shown(k) && <p id={`${k}-error`}><span className="visually-hidden">Error: </span>{errors[k]}</p>}
</div>
))}
<button
type="submit"
onPointerDown={() => { pressingSubmit.current = true; }}
onPointerUp={() => { pressingSubmit.current = false; }}
onPointerLeave={() => { pressingSubmit.current = false; }}
onPointerCancel={() => { pressingSubmit.current = false; }}
>
Create account
</button>
</form>
);
}
The test file renders it with React 18 and Testing Library under jsdom and covers: no error before first blur; blur shows an error wired with aria-invalid and aria-describedby, which clears while typing; the confirm field recomputes when the password changes; a failed submit does not call save, lists four problems in field order and focuses the summary; a summary link focuses its field and fixing everything saves exactly once.
import { describe, it, expect, vi, afterEach } from 'vitest';
import { render, screen, cleanup } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { SignupValidation } from './SignupValidation.jsx';
afterEach(cleanup);
const setup = () => { const save = vi.fn(); const user = userEvent.setup(); render(<SignupValidation save={save} />); return { save, user }; };
const field = (name) => screen.getByLabelText(name);
describe('validation timing', () => {
it('shows nothing while the user is still typing in a field they have not left', async () => {
const { user } = setup();
await user.type(field('Email'), 'ada@');
expect(field('Email').hasAttribute('aria-invalid')).toBe(false);
expect(screen.queryByText(/name@example.com/)).toBeNull();
});
it('validates on blur, links the error to the input, then clears it as soon as the value is fixed', async () => {
const { user } = setup();
await user.type(field('Email'), 'ada@');
await user.tab();
expect(field('Email').getAttribute('aria-invalid')).toBe('true');
const err = document.getElementById(field('Email').getAttribute('aria-describedby'));
expect(err.textContent).toBe('Error: Enter an email address like name@example.com');
await user.type(field('Email'), 'x.com'); // now ada@x.com, validated on every keystroke
expect(field('Email').hasAttribute('aria-invalid')).toBe(false);
expect(field('Email').hasAttribute('aria-describedby')).toBe(false);
});
it('re-checks the confirm field when the password it depends on changes', async () => {
const { user } = setup();
await user.type(field('Password'), 'hunter22!');
await user.type(field('Confirm password'), 'hunter22!x');
await user.tab();
expect(screen.getByText('Passwords do not match', { selector: 'p' })).toBeTruthy();
await user.type(field('Password'), 'x'); // password is now hunter22!x, matching confirm without touching confirm
expect(screen.queryByText('Passwords do not match', { selector: 'p' })).toBeNull();
expect(field('Confirm password').hasAttribute('aria-invalid')).toBe(false);
});
});
describe('failed submit', () => {
it('blocks the save, lists every problem in field order, and focuses the summary', async () => {
const { user, save } = setup();
await user.click(screen.getByRole('button', { name: 'Create account' }));
expect(save).not.toHaveBeenCalled();
const summary = screen.getByRole('alert');
expect(document.activeElement).toBe(summary.parentElement);
const links = [...summary.querySelectorAll('a')].map((a) => [a.textContent, a.getAttribute('href')]);
expect(links).toEqual([
['Enter your full name', '#name'],
['Enter your email address', '#email'],
['Password must be at least 8 characters', '#password'],
['Confirm your password', '#confirm'],
]);
for (const n of ['Full name', 'Email', 'Password', 'Confirm password']) expect(field(n).getAttribute('aria-invalid')).toBe('true');
});
it('a summary link moves focus to its field; fixing everything removes the summary and saves once', async () => {
const { user, save } = setup();
await user.click(screen.getByRole('button', { name: 'Create account' }));
await user.click(screen.getByRole('link', { name: 'Enter your email address' }));
expect(document.activeElement).toBe(field('Email'));
await user.type(field('Full name'), 'Ada Lovelace');
await user.type(field('Email'), 'ada@example.com');
await user.type(field('Password'), 'correct horse');
await user.type(field('Confirm password'), 'correct horse');
expect(screen.queryByRole('alert')).toBeNull();
await user.click(screen.getByRole('button', { name: 'Create account' }));
expect(save).toHaveBeenCalledTimes(1);
});
});
Run with npx vitest run validation, it prints 5 passing tests (Tests 5 passed (5)). Changing the shown rule to display errors before blur makes the first test fail. Deleting the focus() call in the effect fails the first failed-submit test. Replacing setAttempt((n) => n + 1) with setAttempt(1) (a flag instead of a counter) passes all five tests above and is caught only by a sixth test, saved as second.test.jsx next to the others, which follows a summary link to the Email field and then submits again with the same four errors:
import { it, expect, vi, afterEach } from 'vitest';
import { render, screen, cleanup } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { SignupValidation } from './SignupValidation.jsx';
afterEach(cleanup);
it('a second failed submit with the same errors returns focus to the summary', async () => {
const user = userEvent.setup();
render(<SignupValidation save={vi.fn()} />);
const submit = screen.getByRole('button', { name: 'Create account' });
await user.click(submit);
const summary = screen.getByRole('alert').parentElement;
expect(document.activeElement).toBe(summary);
await user.click(screen.getByRole('link', { name: 'Enter your email address' }));
expect(document.activeElement).toBe(screen.getByLabelText('Email')); // focus has left the summary
await user.click(submit); // same four errors as before
expect(document.activeElement).toBe(screen.getByRole('alert').parentElement);
});
Run with npx vitest run (no filter), both files together print 6 passing tests.
jsdom has no layout, so it cannot show one failure that real browsers do: with blur validation, the first error line appears when the pointer goes down on the submit button (the field blurs), pushing the button down before the pointer is released, so the mouse-up lands elsewhere and no click happens. Measured in Playwright 1.48.2 against the earlier version of this component (no pressingSubmit guard): after typing abc into Email and clicking Create account once, no summary appeared in Chromium, Firefox or WebKit, and the button had moved down by about 50 px. The pressingSubmit ref in the code above fixes it: pointer down on the button sets it, pointer up, leave or cancel clears it, and while it is set a blur records nothing, because the click that follows validates every field anyway. Keyboard users are unaffected (no pointer, and the field had already blurred when Tab reached the button). The component is bundled for the browser (commands in Running the code) and checked in all three engines (Playwright 1.48.2):
import { chromium, firefox, webkit } from 'playwright';
import { readFileSync } from 'node:fs';
import assert from 'node:assert/strict';
const bundle = readFileSync(process.argv[2] ?? 'bundle.js', 'utf8');
for (const [name, type] of [['chromium', chromium], ['firefox', firefox], ['webkit', webkit]]) {
const browser = await type.launch();
const page = await browser.newPage();
await page.setContent('<div id="root"></div>');
await page.addScriptTag({ content: bundle });
await page.click('#email');
await page.keyboard.type('abc'); // an invalid email, focus still in the field
await page.click('button'); // ONE real click: mouse down, mouse up
const state = await page.evaluate(() => ({
summaryShown: !!document.querySelector('[role="alert"]'),
focusInSummary: document.activeElement === document.querySelector('[role="alert"]')?.parentElement,
}));
assert.deepEqual(state, { summaryShown: true, focusInSummary: true }, name);
console.log(name, 'one click on the button shows the summary and focuses it');
await browser.close();
}
It printed one line per engine:
chromium one click on the button shows the summary and focuses it
firefox one click on the button shows the summary and focuses it
webkit one click on the button shows the summary and focuses it
With the earlier component (the pressingSubmit lines removed) the assertion fails on the first engine.
Trade-offs
- Validate on blur versus on submit only: blur-first catches mistakes while the field is fresh in the user's mind; submit-only avoids early nagging but produces a wall of errors on a long form. I would ship the hybrid, and drop to submit-only for fields where partial input is normal (promo codes).
- Focus the summary versus the first field: the summary is better on long forms and for screen readers; the first field is better when there is one error and sight-based users benefit from the cursor already being there.
- Pitfalls: an error that appears on blur above the submit button and eats the first click (see the browser check above); marking every required field red on page load; error text that says only "Invalid"; moving focus on every blur; clearing the user's input when an error occurs; relying on colour alone.
Running the code
Tested in a node:22 container.
npm i react@18.3.1 react-dom@18.3.1 jsdom vitest@2.1.8 @testing-library/react@16 @testing-library/dom @testing-library/user-event
npx vitest run validation
vitest.config.js, next to the files: export default { esbuild: { jsx: 'automatic' }, test: { environment: 'jsdom' } }. It lets the JSX compile without a React import and provides document. Without it all the tests fail: those that call userEvent.setup() stop with a TypeError about the missing document, and the rest with ReferenceError: React is not defined.
For the browser check, also npm i esbuild playwright@1.48.2. entry.jsx renders the component: import { createRoot } from 'react-dom/client'; import { SignupValidation } from './SignupValidation.jsx'; createRoot(document.getElementById('root')).render(<SignupValidation save={() => {}} />);. Bundle it with npx esbuild entry.jsx --bundle --jsx=automatic --define:process.env.NODE_ENV='"development"' --outfile=bundle.js, save the harness as check.mjs, and run node check.mjs bundle.js in the mcr.microsoft.com/playwright:v1.48.2-jammy image.
Unlock Full Question Bank
Get access to all 18 UI Component Implementation: Forms and States interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.