Primitiveselection

Radio Group

Stable

Uma resposta dentre um conjunto conhecido. Composto sobre Base UI RadioGroup. É um controle só feito de vários elementos: o grupo custa um Tab stop, e dentro dele as setas movem e escolhem ao mesmo tempo. Não há caminho de volta para "nada" — uma pergunta genuinamente opcional precisa de uma opção explícita, não de um grupo vazio. Passando de seis ou sete opções, o Select passa a economizar mais do que custa.

Instalação

npx up-web-ds add radio-group

Preview

Basic

Distribuição do item

Interna
Restrita

Default

Distribuição do item

With Descriptions

Maturidade

With Disabled Option

Publicação

Cards

Notificações

Horizontal

Tema do preview

All states

Basic

Distribuição do item

Interna
Restrita

Default

Distribuição do item

With Descriptions

Maturidade

With Disabled Option

Publicação

Cards

Notificações

Horizontal

Tema do preview

Usage

Imports de Radio Group
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
import { useId } from 'react'
Radio Group
function DistributionChoice() {
  const uid = useId()
  const groupLabelId = `${uid}-group`
  const internalLabelId = `${uid}-internal`
  const restrictedLabelId = `${uid}-restricted`

  return (
    <div className="flex w-full max-w-sm flex-col gap-3">
      <p id={groupLabelId} className="type-small font-medium">
        Distribuição do item
      </p>

      <RadioGroup aria-labelledby={groupLabelId} defaultValue="internal">
        <div className="flex items-center gap-3">
          <RadioGroupItem value="internal" aria-labelledby={internalLabelId} />
          <span id={internalLabelId} className="type-small">
            Interna
          </span>
        </div>

        <div className="flex items-center gap-3">
          <RadioGroupItem
            value="restricted"
            aria-labelledby={restrictedLabelId}
          />
          <span id={restrictedLabelId} className="type-small">
            Restrita
          </span>
        </div>
      </RadioGroup>
    </div>
  )
}

Props

RadioGroup

Props de RadioGroup
PropTypeDefaultDescription
classNamestring | ((state: RadioGroupState) => string | undefined)sem valor padrãoCSS class applied to the element, or a function that returns a class based on the component's state.
defaultValueanysem valor padrãoThe uncontrolled value of the radio button that should be initially selected. To render a controlled radio group, use the `value` prop instead.
disabledbooleanfalseWhether the component should ignore user interaction.
formstringsem valor padrãoIdentifies the form that owns the radio inputs. Useful when the radio group is rendered outside the form.
inputRefReact.Ref<HTMLInputElement>sem valor padrãoA ref to access the hidden input element.
namestringsem valor padrãoIdentifies the field when a form is submitted.
onValueChange((value: any, eventDetails: RadioGroup.ChangeEventDetails) => void)sem valor padrãoCallback fired when the value changes.
readOnlybooleanfalseWhether the user should be unable to select a different radio button in the group.
renderReact.ReactElement<unknown, string | React.JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, RadioGroupState>sem valor padrãoAllows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render.
requiredbooleanfalseWhether the user must choose a value before submitting a form.
styleReact.CSSProperties | ((state: RadioGroupState) => React.CSSProperties | undefined)sem valor padrãoStyle applied to the element, or a function that returns a style object based on the component's state.
valueanysem valor padrãoThe controlled value of the radio item that should be currently selected. To render an uncontrolled radio group, use the `defaultValue` prop instead.

Estende RadioGroupPrimitive.Props. Aceita também os atributos padrão de um elemento React (275 não listados).

RadioGroupItem

Props de RadioGroupItem
PropTypeDefaultDescription
value, obrigatóriaanysem valor padrãoThe unique identifying value of the radio in a group.
classNamestring | ((state: RadioRootState) => string | undefined)sem valor padrãoCSS class applied to the element, or a function that returns a class based on the component's state.
disabledbooleansem valor padrãoWhether the component should ignore user interaction.
inputRefReact.Ref<HTMLInputElement>sem valor padrãoA ref to access the hidden input element.
nativeButtonbooleanfalseWhether the component renders a native `<button>` element when replacing it via the `render` prop. Set to `true` if the rendered element is a native button.
readOnlybooleansem valor padrãoWhether the user should be unable to select the radio button.
renderReact.ReactElement<unknown, string | React.JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, RadioRootState>sem valor padrãoAllows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render.
requiredbooleansem valor padrãoWhether the user must choose a value before submitting a form.
styleReact.CSSProperties | ((state: RadioRootState) => React.CSSProperties | undefined)sem valor padrãoStyle applied to the element, or a function that returns a style object based on the component's state.

Estende RadioPrimitive.Root.Props. Aceita também os atributos padrão de um elemento React (275 não listados).

prop obrigatória.

Composition

O RadioGroup é quem carrega o valor e o rótulo do conjunto; cada RadioGroupItem é uma opção dentro dele.

Composição de RadioGroup

RadioGroup

  • RadioGroupItem

Metadata

Notas de acessibilidade

Teclado verificado por teste: o grupo inteiro custa um Tab stop — o segundo Tab sai dele —, as setas movem e escolhem ao mesmo tempo, a navegação dá a volta da última opção para a primeira, e uma opção desabilitada continua no grupo recusando a escolha. Leitor de tela verificado por teste: o grupo tem papel radiogroup nomeado pela pergunta via aria-labelledby, cada opção tem papel radio com aria-checked, a escolha é reportada pelo valor, o rótulo associado também escolhe, e aria-invalid é exposto no grupo sem trocar o papel dos controles. Touch verificado em navegador com emulação de toque em viewport de 375px: o círculo visível mede 16x16, mas o alvo desenhado pelo pseudo-elemento mede acima do mínimo de 24x24 da WCAG 2.2 SC 2.5.8, e a escolha por toque funciona pelo círculo e pelo rótulo. Reduced motion verificado com prefers-reduced-motion: reduce — a única transição, a do anel de foco, não é movimento e permanece: remover uma transição de cor não acomoda ninguém e custa a única pista que o estado tem. Nenhum deslocamento existe aqui para ser desligado.

Classificação

Layer
Primitive
Domínio
Domain-free (compartilhado)
Categoria
selection
Status
Stable

Origem e distribuição

Fonte
shadcn registry / radio-group
Licença
MIT
Distribuição
Interna

Acessibilidade

  • Teclado: revisado
  • Leitor de tela: revisado
  • Touch: revisado
  • Reduced motion: revisado

Dependências

Pacotes
@base-ui/react
Ícones
Nenhum
Construído sobre
Nenhum
Usado por
Questionnaire