Primitiveselection

Slider

Stable

Primitive de seleção para escolher um valor, ou um intervalo, ao longo de uma escala. Composto sobre Base UI Slider: cada thumb é um input range de verdade, com teclado e leitor de tela nativos. A quantidade de thumbs segue o valor — um número é um thumb, um array é um por entrada —, e um intervalo nomeia cada ponta com thumbLabels, porque dois controles com o mesmo nome não dizem qual extremo se está segurando. O knob visível tem 16px dentro de um thumb de 24px, que é o alvo real do toque.

Instalação

npx up-web-ds add slider

Preview

Basic

Volume

With Value

Duração da sessão
30 min

Range

Faixa de preço
R$ 200 – R$ 800

Disabled

Limite de upload
40

Vertical

Graves
Médios
Agudos

Without Visible Label

All states

Basic

Volume

With Value

Duração da sessão
30 min

Range

Faixa de preço
R$ 200 – R$ 800

Disabled

Limite de upload
40

Vertical

Graves
Médios
Agudos

Without Visible Label

Usage

@/components/ui/slider
import { Slider, SliderLabel } from '@/components/ui/slider'
Slider
<Slider defaultValue={60}>
  <SliderLabel>Volume</SliderLabel>
</Slider>

Props

Slider

Props de Slider
PropTypeDefaultDescription
thumbLabelsreadonly string[]sem valor padrãoOne accessible name per thumb, in value order. A range is two controls, and "Preço" twice tells a listener nothing about which end they are holding. With a single thumb the name can come from `SliderLabel`, `aria-labelledby` or `aria-label` instead.
classNamestring | ((state: SliderRootState) => string | undefined)sem valor padrãoCSS class applied to the element, or a function that returns a class based on the component's state.
defaultValuenumber | readonly number[]sem valor padrãoThe uncontrolled value of the slider when it's initially rendered. To render a controlled slider, use the `value` prop instead.
disabledbooleanfalseWhether the slider should ignore user interaction.
formstringsem valor padrãoIdentifies the form that owns the slider inputs. Useful when the slider is rendered outside the form.
formatIntl.NumberFormatOptionssem valor padrãoOptions to format the value.
largeStepnumber10The granularity with which the slider can step through values when using Page Up/Page Down or Shift + Arrow Up/Arrow Down.
localeIntl.LocalesArgumentsem valor padrãoThe locale used by `Intl.NumberFormat` when formatting the value. Defaults to the user's runtime locale.
maxnumber100The maximum allowed value of the slider. Should not be equal to min.
minnumber0The minimum allowed value of the slider. Should not be equal to max.
minStepsBetweenValuesnumber0The minimum steps between values in a range slider.
namestringsem valor padrãoIdentifies the field when a form is submitted.
onValueChange((value: number | readonly number[], eventDetails: SliderRoot.ChangeEventDetails) => void)sem valor padrãoCallback function that is fired when the slider's value changed. Receives the new value as the first argument; the originating event is available as `eventDetails.event`. The value is also reflected on `eventDetails.event.target.value` for form integration. The `eventDetails.reason` indicates what triggered the change: - `'input-change'` when the hidden range input emits a change event (for example, via form integration) - `'track-press'` when the control track is pressed - `'drag'` while dragging a thumb - `'keyboard'` for keyboard input - `'none'` when the change is triggered without a specific interaction
onValueCommitted((value: number | readonly number[], eventDetails: SliderRoot.CommitEventDetails) => void)sem valor padrãoCallback function that is fired when a value change is committed. Does not fire if the value did not change, or if the change was canceled. **Warning**: This is a generic event, not a change event. The `eventDetails.reason` indicates what triggered the commit: - `'drag'` while dragging a thumb - `'track-press'` when the control track is pressed - `'keyboard'` for keyboard input - `'input-change'` when the hidden range input emits a change event (for example, via form integration) - `'none'` when the commit occurs without a specific interaction
orientationOrientation'horizontal'The component orientation.
renderReact.ReactElement<unknown, string | React.JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SliderRootState>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.
stepnumber1The granularity with which the slider can step through values. (A "discrete" slider.) The `min` prop serves as the origin for the valid values. We recommend (max - min) to be evenly divisible by the step.
styleReact.CSSProperties | ((state: SliderRootState) => 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.
thumbAlignment"center" | "edge" | "edge-client-only"'center'How the thumb(s) are aligned relative to `Slider.Control` when the value is at `min` or `max`: - `center`: The center of the thumb is aligned with the control edge - `edge`: The thumb is inset within the control such that its edge is aligned with the control edge - `edge-client-only`: Same as `edge` but renders after React hydration on the client, reducing bundle size in return
thumbCollisionBehavior"none" | "push" | "swap"'push'Controls how thumbs behave when they collide during pointer interactions. - `'push'` (default): Thumbs push each other without restoring their previous positions when dragged back. - `'swap'`: Thumbs swap places when dragged past each other. - `'none'`: Thumbs cannot move past each other; excess movement is ignored.
valuenumber | readonly number[]sem valor padrãoThe value of the slider. For range sliders, provide an array with one value per thumb.

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

SliderLabel

Props de SliderLabel
PropTypeDefaultDescription
classNamestring | ((state: SliderRootState) => string | undefined)sem valor padrãoCSS class applied to the element, or a function that returns a class based on the component's state.
renderReact.ReactElement<unknown, string | React.JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SliderRootState>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.
styleReact.CSSProperties | ((state: SliderRootState) => 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 SliderPrimitive.Label.Props. Aceita também os atributos padrão de um elemento React (274 não listados).

SliderValue

Props de SliderValue
PropTypeDefaultDescription
children((formattedValues: readonly string[], values: readonly number[]) => React.ReactNode) | nullsem valor padrão
classNamestring | ((state: SliderValueState) => string | undefined)sem valor padrãoCSS class applied to the element, or a function that returns a class based on the component's state.
renderReact.ReactElement<unknown, string | React.JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SliderValueState>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.
styleReact.CSSProperties | ((state: SliderValueState) => 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 SliderPrimitive.Value.Props. Aceita também os atributos padrão de um elemento React (277 não listados).

Composition

Rótulo e leitura são filhos opcionais do Slider, desenhados antes do controle; trilha, preenchimento e thumbs são do próprio Slider, um thumb por valor.

Composição de Slider

Slider

  • SliderLabel
  • SliderValue

Metadata

Notas de acessibilidade

Teclado verificado por teste: cada thumb é alcançável por Tab, as setas movem um passo (Direita e Cima aumentam, Esquerda e Baixo diminuem, inclusive no vertical), Page Up e Page Down dão o passo largo e Home e End levam às pontas; num intervalo cada thumb se move sozinho e o inferior vem primeiro na ordem de tabulação. Um slider desabilitado sai da sequência de tabulação e recusa o teclado sem deixar de reportar o valor. Leitor de tela verificado por teste: o papel é slider, com min, max e aria-valuenow; o nome vem do SliderLabel, ligado pelo Base UI sem id no exemplo, ou de aria-label — que o Base UI deixava só no group e aqui chega também ao thumb, que é onde o foco pousa. Num intervalo, thumbLabels nomeia cada ponta e o valor é lido sozinho; sem nomes próprios, o valor falado diz "início do intervalo" e "fim do intervalo" em vez do inglês "start range" do Base UI. O SliderValue é um output ligado aos thumbs e não é live region, porque o thumb já anuncia o próprio valor. Touch verificado em viewport de 375px com emulação de toque: o thumb mede 24x24 — o knob pintado tem 16px e o box que o Base UI posiciona, e que contém o input, é o alvo —, o controle tem ao menos a mesma altura e um toque na trilha move o valor. A origem pendurava a orientação em data-vertical, que o Base UI não emite; o vertical agora é de fato mais alto que largo, verificado em navegador. Reduced motion verificado em navegador com prefers-reduced-motion: reduce — a posição do thumb é escrita inline pelo Base UI e nunca teve tween, então chega ao destino na hora; o anel de hover e foco no knob é resposta de cor e sombra, não movimento, e permanece.

Classificação

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

Origem e distribuição

Fonte
shadcn registry / slider
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