Primitiveselection

Switch

Stable

Controle que faz efeito no instante em que se move. Composto sobre Base UI Switch. A distinção para o Checkbox não é de forma e sim de produto: switch pertence a um ajuste que se aplica na hora, checkbox a um valor enviado com o formulário — uma fileira de switches acima de um botão Salvar é uma promessa que a interface não cumpre. A pista visível é menor que o alvo: um pseudo-elemento estende a área de toque para fora da trilha sem mexer no layout ao redor.

Instalação

npx up-web-ds add switch

Preview

Basic

Validar ao salvar

Default

Sizes

States

Settings List

All states

Basic

Validar ao salvar

Default

Sizes

States

Settings List

Usage

Imports de Switch
import { Switch } from '@/components/ui/switch'
import { useId } from 'react'
Switch
function ValidateOnSave() {
  const labelId = useId()

  return (
    <div className="flex items-center gap-3">
      <Switch aria-labelledby={labelId} defaultChecked />
      <span id={labelId} className="type-small font-medium">
        Validar ao salvar
      </span>
    </div>
  )
}

Props

Props de Switch
PropTypeDefaultDescription
size"default" | "sm"'default'
checkedbooleansem valor padrãoWhether the switch is currently active. To render an uncontrolled switch, use the `defaultChecked` prop instead.
classNamestring | ((state: SwitchRootState) => string | undefined)sem valor padrãoCSS class applied to the element, or a function that returns a class based on the component's state.
defaultCheckedbooleanfalseWhether the switch is initially active. To render a controlled switch, use the `checked` prop instead.
disabledbooleanfalseWhether the component should ignore user interaction.
formstringsem valor padrãoIdentifies the form that owns the hidden input. Useful when the switch is rendered outside the form.
idstringsem valor padrãoThe id of the hidden input element. When `nativeButton` is `true`, the id is applied to the root element.
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.
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.
onCheckedChange((checked: boolean, eventDetails: SwitchRoot.ChangeEventDetails) => void)sem valor padrãoEvent handler called when the switch is activated or deactivated.
readOnlybooleanfalseWhether the user should be unable to activate or deactivate the switch.
renderReact.ReactElement<unknown, string | React.JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SwitchRootState>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 activate the switch before submitting a form.
styleReact.CSSProperties | ((state: SwitchRootState) => 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.
uncheckedValuestringsem valor padrãoThe value submitted with the form when the switch is off. By default, unchecked switches do not submit any value, matching native checkbox behavior.
valuestringsem valor padrãoThe value submitted with the form when the switch is on. By default, switch submits the "on" value, matching native checkbox behavior.

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

Metadata

Notas de acessibilidade

Teclado verificado por teste: alcançável por Tab, Space e Enter alternam, e um switch desabilitado sai da sequência de tabulação recusando a alternância sem deixar de reportar o estado. Leitor de tela verificado por teste: o papel é switch e não checkbox, o nome vem do label associado — a trilha não tem texto próprio —, aria-checked carrega o estado em vez de a cor sozinha, e aria-invalid é exposto sem trocar o papel do controle. Touch verificado em navegador com emulação de toque em viewport de 375px: a trilha visível mede 36x20 no tamanho default e 28x16 no sm, mas o alvo desenhado pelo pseudo-elemento mede acima do mínimo de 24x24 da WCAG 2.2 SC 2.5.8 nos dois, e o toque alterna. Reduced motion verificado com prefers-reduced-motion: reduce — a posição do thumb é o estado, então ela nunca é condicionada: sob reduce o thumb continua indo para a ponta marcada, só sem o tween (motion-reduce:transition-none). Movimento não é o único sinal aqui — a cor da trilha e o anel de foco dizem o mesmo.

Classificação

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

Origem e distribuição

Fonte
shadcn registry / switch
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
Nenhum ainda