Components

Radio Group

One of a few, all in view: round marks in a hairline, the picked one edged in White with a White dot. Arrows move the pick.

Install

React apps get the React files; every other stack gets the web component.

npx spyglass-ds add radio-group
<script type="module" src="/spyglass-ds/elements/radio-group.js"></script>
With hints

Who can see this board

In a row

Usage

A pick of one from two to five choices that each need a word of explanation: who can see a board, how often to send a digest.

Never

  • More than five options: use Native Select or Select
  • Views of one thing: use Tabs
  • A spectrum color for the picked mark

Props

The web component takes the same as attributes or properties (<spyglass-radio-group>); title is heading there.

<RadioGroup>

PropTypeDefault
optionsRadioOption<T>[]

The choices: value, label, an optional hint, disabled.

labelstring

The group's name for assistive tech.

namestring

The form field's name (also the radios' group).

inlineboolean

The options in a row.

disabledboolean
valueT
defaultValueT
onValueChange(value: T) => void
classNamestring

Examples

The same example in React and as web components; both render identically.

react/examples/radio-group/Visibility.tsx
import { RadioGroup } from '@/react/components/ui/RadioGroup'
// Who can see a board: three choices with a line each, and one locked by the plan.

export default function Visibility() {
  return (
    <div className="flex w-96 max-w-full flex-col gap-3">
      <p className="type-label text-fg-soft">Who can see this board</p>
      <RadioGroup
        label="Who can see this board"
        name="visibility"
        defaultValue="team"
        options={[
          { value: 'private', label: 'Only you', hint: 'Nobody else sees it until you share it.' },
          { value: 'team', label: 'Your team', hint: 'Everyone at Acme can open and add to it.' },
          { value: 'link', label: 'Anyone with the link', hint: 'Available on the Team plan.', disabled: true },
        ]}
      />
    </div>
  )
}
elements/examples/radio-group/Visibility.html
<!-- Who can see a board: three choices with a line each, and one locked by the plan. -->
<div class="flex w-96 max-w-full flex-col gap-3">
  <p class="type-label text-fg-soft">Who can see this board</p>
  <spyglass-radio-group label="Who can see this board" name="visibility" value="team" options='[{"value":"private","label":"Only you","hint":"Nobody else sees it until you share it."},{"value":"team","label":"Your team","hint":"Everyone at Acme can open and add to it."},{"value":"link","label":"Anyone with the link","hint":"Available on the Team plan.","disabled":true}]'></spyglass-radio-group>
</div>
react/examples/radio-group/Inline.tsx
import { RadioGroup } from '@/react/components/ui/RadioGroup'
// A sort order in a row, over a grid of creatives.

export default function Inline() {
  return (
    <RadioGroup
      label="Sort creatives"
      inline
      defaultValue="spend"
      options={[
        { value: 'spend', label: 'Spend' },
        { value: 'new', label: 'Newest' },
        { value: 'running', label: 'Longest running' },
      ]}
    />
  )
}
elements/examples/radio-group/Inline.html
<!-- A sort order in a row, over a grid of creatives. -->
<spyglass-radio-group label="Sort creatives" inline value="spend" options='[{"value":"spend","label":"Spend"},{"value":"new","label":"Newest"},{"value":"running","label":"Longest running"}]'></spyglass-radio-group>

Source

react/components/ui/RadioGroup.tsx
'use client'
import { useId } from 'react'
import { useControllable } from '@/react/hooks/useControllable'

// One of a few, all in view: 16px circles in the #666666 hairline (round, as the lens in the logomark; every other
// control keeps the brand corner), the picked one edged in White with a White 8px dot that settles in from 0.6 over
// 160ms on the strong ease-out (reduced motion fades it). Rows 32px (44px on phones) with a DM Sans label and an
// optional muted hint. Arrows move the pick, as native radios do; focus is the White ring. More than five options is a
// Native Select or a Select; views of one thing are Tabs. `value` with `onValueChange` controls it (or `defaultValue`).
export interface RadioOption<T extends string> { value: T, label: string, hint?: string, disabled?: boolean }
export interface RadioGroupProps<T extends string> {
  /** The choices: value, label, an optional hint, disabled. */
  options: RadioOption<T>[]
  /** The group's name for assistive tech. */
  label: string
  /** The form field's name (also the radios' group). */
  name?: string
  /** The options in a row. */
  inline?: boolean
  disabled?: boolean
  value?: T
  defaultValue?: T
  onValueChange?: (value: T) => void
  className?: string
}

export function RadioGroup<T extends string>({ options, label, name: given, inline, disabled, value, defaultValue, onValueChange, className }: RadioGroupProps<T>) {
  const [model, setModel] = useControllable<T | undefined>(value, defaultValue, v => v !== undefined && onValueChange?.(v))
  const auto = useId()
  const name = given ?? `radio-${auto}`
  return (
    <>
      <style href="ds-radio-group" precedence="ds">{css}</style>
      <div data-ds="radio-group" role="radiogroup" aria-label={label} className={className ? `ds-radios ${className}` : 'ds-radios'} data-inline={inline || undefined}>
        {options.map(o => (
          <label key={o.value} className="ds-radiorow" data-disabled={disabled || o.disabled || undefined}>
            <span className="ds-radio"><input type="radio" name={name} value={o.value} checked={model === o.value} onChange={() => setModel(o.value)} disabled={disabled || o.disabled} aria-describedby={o.hint ? `${name}-${o.value}` : undefined} /><i aria-hidden="true" /></span>
            <span className="flex min-w-0 flex-col">
              <span>{o.label}</span>
              {o.hint && <span id={`${name}-${o.value}`} className="type-caption text-fg-muted">{o.hint}</span>}
            </span>
          </label>
        ))}
      </div>
    </>
  )
}

export default RadioGroup

const css = `
.ds-radios { display: flex; flex-direction: column; gap: var(--ds-space-xs); }
.ds-radios[data-inline] { flex-direction: row; flex-wrap: wrap; column-gap: var(--ds-space-xl); }
.ds-radiorow { display: inline-flex; min-height: var(--ds-size-control-sm); align-items: flex-start; gap: var(--ds-space-md); padding-block: var(--ds-space-xs); color: var(--ds-color-fg); font-family: var(--ds-font-text); font-size: var(--ds-text-ui); line-height: var(--ds-text-ui-leading); cursor: pointer; }
.ds-radiorow[data-disabled] { color: var(--ds-color-fg-faint); cursor: not-allowed; }
.ds-radio { display: inline-grid; width: var(--ds-size-icon-sm); height: var(--ds-size-icon-sm); flex-shrink: 0; margin-top: var(--ds-space-2xs); place-items: center; }
.ds-radio > * { grid-area: 1 / 1; }
.ds-radio > input { width: var(--ds-size-icon-sm); height: var(--ds-size-icon-sm); margin: 0; border: var(--ds-border-hairline) solid var(--ds-color-edge-strong); border-radius: var(--ds-radius-full); background: var(--ds-color-surface); appearance: none; cursor: inherit; transition: border-color var(--ds-duration-micro) var(--ds-easing-standard); }
.ds-radio > input:checked { border-color: var(--ds-color-action-primary); }
.ds-radio > input:focus-visible { outline: var(--ds-border-focus) solid var(--ds-color-edge-focus); outline-offset: var(--ds-border-focus); }
.ds-radio > input:disabled { border-color: var(--ds-color-edge); background: var(--ds-color-surface-sunken); }
.ds-radio > i { width: var(--ds-space-sm); height: var(--ds-space-sm); border-radius: var(--ds-radius-full); background: var(--ds-color-action-primary); opacity: 0; pointer-events: none; transform: scale(0.6); transition: opacity var(--ds-duration-micro) var(--ds-easing-out), transform var(--ds-duration-micro) var(--ds-easing-out); }
.ds-radio > input:checked + i { opacity: 1; transform: none; }
.ds-radio > input:disabled + i { background: var(--ds-color-fg-faint); }
@media (hover: hover) and (pointer: fine) { .ds-radiorow:hover > .ds-radio > input:not(:disabled, :checked) { border-color: var(--ds-color-action-secondary-edge-hover); } }
@media (pointer: coarse), (max-width: 767px) { .ds-radiorow { min-height: var(--ds-size-control-touch); align-items: center; padding-block: var(--ds-space-sm); font-size: var(--ds-text-body); line-height: var(--ds-text-body-leading); } .ds-radio { margin-top: 0; } }
@media (prefers-reduced-motion: reduce) { .ds-radio > i { transform: none; transition: opacity var(--ds-duration-micro) var(--ds-easing-standard); } }
`
react/hooks/useControllable.ts
'use client'
import { useCallback, useRef, useState } from 'react'

// Vue's defineModel in React: a value that is controlled when the caller passes it (value + onValueChange, as Radix
// does) and kept inside otherwise (defaultValue). setValue calls onChange either way.
export function useControllable<T>(value: T | undefined, defaultValue: T, onChange?: (value: T) => void) {
	const [inner, setInner] = useState<T>(defaultValue)
	const controlled = value !== undefined
	const current = controlled ? value : inner
	const ref = useRef(onChange)
	ref.current = onChange
	const set = useCallback((next: T) => {
		if (!controlled) setInner(next)
		ref.current?.(next)
	}, [controlled])
	return [current, set] as const
}
elements/components/ui/radio-group.ts
import { html, LitElement, nothing, type PropertyValues } from 'lit'
import { ifDefined } from 'lit/directives/if-defined.js'
import { live } from 'lit/directives/live.js'
import { DsFormElement, define, uid } from '@/elements/lib/element'
import styles from 'virtual:tw'

// RadioGroup.tsx as <spyglass-radio-group>: one of a few, all in view: 16px circles in the #666666 hairline, the picked
// one edged in White with a White 8px dot that settles in from 0.6 over 160ms (reduced motion fades it), rows 32px (44px
// on phones) with a DM Sans label and an optional muted hint. Arrows move the pick, as native radios do. `options` is a
// JSON attribute or a property; the value is `value` with the native `input` and `change` events. Form-associated: its
// `name` goes with the form as the picked value.

export interface RadioOption { value: string, label: string, hint?: string, disabled?: boolean }

/**
 * @summary One of a few, all in view.
 * @fires input - The pick moved (read `value`).
 * @fires change - The pick moved (read `value`).
 */
export class RadioGroup extends DsFormElement {
	static styles = [DsFormElement.styles, styles]
	static shadowRootOptions = { ...LitElement.shadowRootOptions, delegatesFocus: true }
	static dsField = true
	static properties = { options: { type: Array }, label: {}, name: {}, inline: { type: Boolean }, disabled: { type: Boolean, reflect: true }, required: { type: Boolean }, value: {} }

	options: RadioOption[] = []
	/** The group's name for assistive tech. */
	label = ''
	/** The form field's name (also the radios' group). */
	name?: string
	/** The options in a row. */
	inline = false
	disabled = false
	value?: string
	/** One must be picked for its form to send. */
	required = false
	private group = uid('radio')

	protected updated(changed: PropertyValues) {
		super.updated(changed)
		if (changed.has('value')) this.internals.setFormValue(this.value ?? null)
	}
	// A group's missing pick is on every radio in it: the first one that can be picked reports it.
	protected validityControl() {
		return this.renderRoot.querySelector<HTMLInputElement>('input:not(:disabled)')
	}
	formResetCallback() {
		this.value = this.getAttribute('value') ?? undefined
	}
	// The inner input event crosses the shadow root on its own (the value is set by then); change does not.
	private onChange() {
		this.dispatchEvent(new Event('change', { bubbles: true, composed: true }))
	}

	render() {
		const name = this.name ?? this.group
		return html`<div data-ds="radio-group" role="radiogroup" aria-label=${this.label} class="ds-radios" data-inline=${ifDefined(this.inline ? 'true' : undefined)}>${this.options.map((o) => html`<label class="ds-radiorow" data-disabled=${ifDefined(this.inactive || o.disabled ? 'true' : undefined)}>
				<span class="ds-radio"><input type="radio" name=${name} .value=${o.value} .checked=${live(this.value === o.value)} ?disabled=${this.inactive || !!o.disabled} ?required=${this.required} aria-describedby=${ifDefined(o.hint ? `${name}-${o.value}` : undefined)} @input=${() => { this.value = o.value }} @change=${this.onChange}><i aria-hidden="true"></i></span>
				<span class="flex min-w-0 flex-col">
					<span>${o.label}</span>
					${o.hint ? html`<span id=${`${name}-${o.value}`} class="type-caption text-fg-muted">${o.hint}</span>` : nothing}
				</span>
			</label>`)}</div>`
	}
}

define('radio-group', RadioGroup)
elements/components/ui/radio-group.css
/* RadioGroup.tsx's styles, as they are. */
.ds-radios { display: flex; flex-direction: column; gap: var(--ds-space-xs); }
.ds-radios[data-inline] { flex-direction: row; flex-wrap: wrap; column-gap: var(--ds-space-xl); }
.ds-radiorow { display: inline-flex; min-height: var(--ds-size-control-sm); align-items: flex-start; gap: var(--ds-space-md); padding-block: var(--ds-space-xs); color: var(--ds-color-fg); font-family: var(--ds-font-text); font-size: var(--ds-text-ui); line-height: var(--ds-text-ui-leading); cursor: pointer; }
.ds-radiorow[data-disabled] { color: var(--ds-color-fg-faint); cursor: not-allowed; }
.ds-radio { display: inline-grid; width: var(--ds-size-icon-sm); height: var(--ds-size-icon-sm); flex-shrink: 0; margin-top: var(--ds-space-2xs); place-items: center; }
.ds-radio > * { grid-area: 1 / 1; }
.ds-radio > input { width: var(--ds-size-icon-sm); height: var(--ds-size-icon-sm); margin: 0; border: var(--ds-border-hairline) solid var(--ds-color-edge-strong); border-radius: var(--ds-radius-full); background: var(--ds-color-surface); appearance: none; cursor: inherit; transition: border-color var(--ds-duration-micro) var(--ds-easing-standard); }
.ds-radio > input:checked { border-color: var(--ds-color-action-primary); }
.ds-radio > input:focus-visible { outline: var(--ds-border-focus) solid var(--ds-color-edge-focus); outline-offset: var(--ds-border-focus); }
.ds-radio > input:disabled { border-color: var(--ds-color-edge); background: var(--ds-color-surface-sunken); }
.ds-radio > i { width: var(--ds-space-sm); height: var(--ds-space-sm); border-radius: var(--ds-radius-full); background: var(--ds-color-action-primary); opacity: 0; pointer-events: none; transform: scale(0.6); transition: opacity var(--ds-duration-micro) var(--ds-easing-out), transform var(--ds-duration-micro) var(--ds-easing-out); }
.ds-radio > input:checked + i { opacity: 1; transform: none; }
.ds-radio > input:disabled + i { background: var(--ds-color-fg-faint); }
@media (hover: hover) and (pointer: fine) { .ds-radiorow:hover > .ds-radio > input:not(:disabled, :checked) { border-color: var(--ds-color-action-secondary-edge-hover); } }
@media (pointer: coarse), (max-width: 767px) { .ds-radiorow { min-height: var(--ds-size-control-touch); align-items: center; padding-block: var(--ds-space-sm); font-size: var(--ds-text-body); line-height: var(--ds-text-body-leading); } .ds-radio { margin-top: 0; } }
@media (prefers-reduced-motion: reduce) { .ds-radio > i { transform: none; transition: opacity var(--ds-duration-micro) var(--ds-easing-standard); } }

Reference: Derived from the brand guidelines (no radio in the brand assets): White for the picked state, the neutral steps for the hairline, the circle of the logomark's lens.