TSX
Public
Accessible Form Fields with useId
Generate stable IDs for reusable form controls and accessible help text.
#react
#accessibility
#form
#typescript
TSX
import { useId } from 'react';
type TextFieldProps = {
label: string;
name: string;
helpText?: string;
};
export function TextField({
label,
name,
helpText,
}: TextFieldProps) {
const inputId = useId();
const helpId = `${inputId}-help`;
return (
<div>
<label htmlFor={inputId}>{label}</label>
<input
id={inputId}
name={name}
aria-describedby={helpText ? helpId : undefined}
/>
{helpText && (
<small id={helpId}>
{helpText}
</small>
)}
</div>
);
}