Component
Radio With Error
Radio with an associated validation message; sets aria-invalid and links the error via aria-describedby.
- Component
- React
- TSX
- Tailwind CSS
- MIT
Preview
Live component
9:41 100%
devsnips.dev/library/react/components/radios/radio-with-error/ fluid · no fixed width 100%
Install
Add to your project
npx devsnips add React/Components/Radios/radio-with-error React/Components/Radios/radio-with-error import type { ChangeEvent, ReactNode } from "react";
import { useId, useState } from "react";
function cx(...parts: Array<string | false | null | undefined>): string {
return parts.filter(Boolean).join(" ");
}
export interface RadioWithErrorProps {
label: ReactNode;
error?: string;
helperText?: ReactNode;
checked?: boolean;
defaultChecked?: boolean;
onChange?: (event: ChangeEvent<HTMLInputElement>) => void;
disabled?: boolean;
required?: boolean;
name?: string;
value: string | number | readonly string[];
id?: string;
className?: string;
}
/**
* Radio with an associated validation message. Sets `aria-invalid="true"` and
* links the error message with `aria-describedby`, so the failure is
* communicated beyond color. The control border + dot take the destructive
* token. Built on the native `<input type="radio">`.
*/
export function RadioWithError({
label,
error,
helperText,
checked,
defaultChecked,
onChange,
disabled,
required,
name,
value,
id,
className,
}: RadioWithErrorProps) {
const generatedId = useId();
const inputId = id ?? `radio-${generatedId}`;
const messageId = `${inputId}-msg`;
const isControlled = checked !== undefined;
const [internal, setInternal] = useState<boolean>(defaultChecked ?? false);
const isChecked = isControlled ? checked : internal;
const hasError = Boolean(error);
function handleChange(event: ChangeEvent<HTMLInputElement>) {
if (!isControlled) setInternal(event.target.checked);
onChange?.(event);
}
return (
<div className={cx("flex flex-col gap-1", className)}>
<label
htmlFor={inputId}
className={cx(
"inline-flex items-center gap-2.5 text-sm leading-5 text-[var(--ds-color-foreground)]",
disabled ? "cursor-not-allowed opacity-60" : "cursor-pointer",
)}
>
<span className="relative inline-flex size-[18px] shrink-0 items-center justify-center">
<input
id={inputId}
type="radio"
aria-invalid={hasError ? true : undefined}
aria-describedby={hasError || helperText ? messageId : undefined}
className={cx(
"size-[18px] cursor-pointer appearance-none rounded-full border bg-[var(--ds-color-input)] transition-colors duration-150 ease-out hover:border-[var(--ds-color-border-strong)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--ds-color-focus-ring)] disabled:cursor-not-allowed disabled:opacity-50 motion-reduce:transition-none",
hasError
? "border-[var(--ds-color-destructive)]"
: "border-[var(--ds-color-border)] checked:border-[var(--ds-color-primary)]",
)}
checked={isControlled ? isChecked : undefined}
defaultChecked={isControlled ? undefined : defaultChecked}
disabled={disabled}
required={required}
name={name}
value={value}
onChange={handleChange}
/>
<span
aria-hidden="true"
className={cx(
"pointer-events-none absolute inset-0 flex items-center justify-center transition-opacity duration-150 motion-reduce:transition-none",
isChecked ? "opacity-100" : "opacity-0",
)}
>
<span
className={cx(
"block size-[8px] rounded-full",
hasError ? "bg-[var(--ds-color-destructive)]" : "bg-[var(--ds-color-primary)]",
)}
/>
</span>
</span>
<span className="select-none">
{label}
{required ? (
<span aria-hidden="true" className="ml-0.5 text-[var(--ds-color-destructive)]">*</span>
) : null}
</span>
</label>
{hasError ? (
<p id={messageId} role="alert" className="pl-[26px] text-xs leading-4 text-[var(--ds-color-destructive)]">
{error}
</p>
) : helperText ? (
<p id={messageId} className="pl-[26px] text-xs leading-4 text-[var(--ds-color-muted-foreground)]">
{helperText}
</p>
) : null}
</div>
);
}
export default RadioWithError; /* DevSnips React — JavaScript parity build.
* Same API, behavior, and classes as code.tsx; TypeScript types removed.
* Regenerated from code.tsx — edit code.tsx and re-run the generator.
*/
import { useId, useState } from "react";
function cx(...parts) {
return parts.filter(Boolean).join(" ");
}
export function RadioWithError({
label,
error,
helperText,
checked,
defaultChecked,
onChange,
disabled,
required,
name,
value,
id,
className
}) {
const generatedId = useId();
const inputId = id ?? `radio-${generatedId}`;
const messageId = `${inputId}-msg`;
const isControlled = checked !== undefined;
const [internal, setInternal] = useState(defaultChecked ?? false);
const isChecked = isControlled ? checked : internal;
const hasError = Boolean(error);
function handleChange(event) {
if (!isControlled) setInternal(event.target.checked);
onChange?.(event);
}
return <div className={cx("flex flex-col gap-1", className)}>
<label
htmlFor={inputId}
className={cx(
"inline-flex items-center gap-2.5 text-sm leading-5 text-[var(--ds-color-foreground)]",
disabled ? "cursor-not-allowed opacity-60" : "cursor-pointer"
)}
>
<span className="relative inline-flex size-[18px] shrink-0 items-center justify-center">
<input
id={inputId}
type="radio"
aria-invalid={hasError ? true : undefined}
aria-describedby={hasError || helperText ? messageId : undefined}
className={cx(
"size-[18px] cursor-pointer appearance-none rounded-full border bg-[var(--ds-color-input)] transition-colors duration-150 ease-out hover:border-[var(--ds-color-border-strong)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--ds-color-focus-ring)] disabled:cursor-not-allowed disabled:opacity-50 motion-reduce:transition-none",
hasError ? "border-[var(--ds-color-destructive)]" : "border-[var(--ds-color-border)] checked:border-[var(--ds-color-primary)]"
)}
checked={isControlled ? isChecked : undefined}
defaultChecked={isControlled ? undefined : defaultChecked}
disabled={disabled}
required={required}
name={name}
value={value}
onChange={handleChange}
/>
<span
aria-hidden="true"
className={cx(
"pointer-events-none absolute inset-0 flex items-center justify-center transition-opacity duration-150 motion-reduce:transition-none",
isChecked ? "opacity-100" : "opacity-0"
)}
>
<span
className={cx(
"block size-[8px] rounded-full",
hasError ? "bg-[var(--ds-color-destructive)]" : "bg-[var(--ds-color-primary)]"
)}
/>
</span>
</span>
<span className="select-none">
{label}
{required ? <span aria-hidden="true" className="ml-0.5 text-[var(--ds-color-destructive)]">*</span> : null}
</span>
</label>
{hasError ? <p id={messageId} role="alert" className="pl-[26px] text-xs leading-4 text-[var(--ds-color-destructive)]">
{error}
</p> : helperText ? <p id={messageId} className="pl-[26px] text-xs leading-4 text-[var(--ds-color-muted-foreground)]">
{helperText}
</p> : null}
</div>;
}
export default RadioWithError; # Radio With Error
Radio with an associated validation message; sets aria-invalid and links the error via aria-describedby.
## Usage
```tsx
<RadioWithError label="Production" error="Production is currently unavailable." name="env" value="production" />
```
## JavaScript
A `code.jsx` build is provided for projects that ship plain JSX. It exposes the same API and behavior as `code.tsx` — only the TypeScript types are removed.
```jsx
<RadioWithError label="Production" error="Production is currently unavailable." name="env" value="production" />
```
## Props
| Name | Type | Default | Description |
|---|---|---:|---|
| `label` | `ReactNode` (required) | — | Visible label (omit for an icon-only / aria-label control). |
| `checked` / `defaultChecked` | `boolean` | `false` | Controlled / uncontrolled checked state. |
| `onChange` | `(event) => void` | — | Change callback. |
| `disabled` | `boolean` | — | Disables the control. |
| `required` | `boolean` | — | Marks the field required (renders `*`). |
| `invalid` | `boolean` | — | Sets `aria-invalid` + destructive styling. |
| `name` | `string` | — | Shared group name (groups radios). |
| `value` | `string \| number \| readonly string[]` (required) | — | Native form value. |
| `id` | `string` | generated | Input id (also the label `htmlFor`). |
| `aria-label` / `aria-labelledby` / `aria-describedby` | `string` | — | Override association. |
| `error` | `string` | — | Error message (sets `aria-invalid`, destructive styling, `role="alert"`). |
| `helperText` | `ReactNode` | — | Shown when no error is present. |
## States
Native radio with an optional error message. When `error` is set the input gets `aria-invalid="true"`, the border + dot take the destructive token, and the message is rendered with `role="alert"` and `aria-describedby`. The failure is communicated by border, dot, and text — not color alone.
## Accessibility
`aria-invalid="true"` + `aria-describedby={messageId}` on the native input; error paragraph carries `role="alert"`. Visible `focus-visible` ring.
## Styling
Built with React, Tailwind CSS, and DevSnips design tokens. The component consumes the `--ds-*` semantic tokens via arbitrary values (for example `bg-[var(--ds-color-primary)]`). Define the tokens once in your theme — no component-specific CSS file is required.
## Design Tokens
See [React/DESIGN_TOKENS.md](../../../DESIGN_TOKENS.md) for the authoritative token specification. This radio uses the semantic color, radius, spacing, and motion tokens.
## Notes
The error state never relies on color alone — the border, the dot, and the message all change. Swap `error` for `helperText` to return to a neutral helper. 120 lines UTF-8 · LF · Spaces: 2
Continue browsing