Slider
A slider for a value where the position on a scale matters more than the exact number: a volume, a threshold, a price range. One thumb holds a value, two hold a range. When the exact number matters, or the scale has no ends, use the number input.
Install
npx shadcn@latest add https://thrumui.dev/r/slider.jsonAdds components/ui/slider.tsx and installs @base-ui/react@1.9.0. Nothing else in your project changes.
import { Slider } from "@/components/ui/slider";Data shape
// Passed as `marks`. Pass `true` instead for a bare tick at every step.
type SliderMark = {
value: number; // where the tick sits, on the slider's scale
label?: string; // text under the tick
};const MARKS = [
{ value: 0, label: "0%" },
{ value: 50, label: "50%" },
{ value: 100, label: "100%" },
];Props
| Prop | Type | Default | Description |
|---|---|---|---|
value | number | readonly number[] | – | The value, when the parent holds it. A list of two numbers makes a range with two thumbs. Use it with onValueChange. |
defaultValue | number | readonly number[] | – | The value at first, when the slider holds it itself. A list makes a range. |
onValueChange | (value) => void | – | Called with the new value on every step while dragging, on key presses and on a press on the track. It has the shape of value: a number or a list. |
onValueCommitted | (value) => void | – | Called once when the change is final: on pointer release and after a key press. Save here, not on every step. |
min | number | Default 0 | The low end of the scale. |
max | number | Default 100 | The high end of the scale. |
step | number | Default 1 | The distance between the values the thumb can stop at, counted from min. |
largeStep | number | Default 10 | How far Page Up, Page Down and Shift with an arrow key move the thumb. |
minStepsBetweenValues | number | Default 0 | Range only: the fewest steps the two thumbs keep between them. |
thumbCollisionBehavior | "push" | "swap" | "none" | Default "push" | Range only: what a dragged thumb does when it meets the other one. |
thumbAlignment | "center" | "edge" | "edge-client-only" | Default "center" | Where a thumb at min or max sits. The slider pads its track by half a thumb, so the default already stays inside the box. |
orientation | "horizontal" | "vertical" | Default "horizontal" | A vertical slider is 192 pixels tall unless className sets another height. Its low end is at the bottom. |
format | Intl.NumberFormatOptions | – | How the value is printed in the bubble and read by screen readers: currency, percent, unit, fraction digits. |
locale | string | Default "en-US" | The locale that prints the value. |
marks | boolean | readonly SliderMark[] | Default false | true draws a tick at every step, when there are 50 steps or fewer. A list draws a tick at each value, with its label underneath. |
valueLabel | "auto" | "on" | "off" | Default "auto" | The value in a bubble over the thumb: auto shows it while the thumb is hovered, focused or dragged. on shows it always and reserves 36 pixels above a horizontal track. |
thumbLabels | readonly string[] | Default ["Minimum", "Maximum"] | Range only: the name of each thumb for screen readers, in order. |
name | string | – | The field name when the slider sits in a form. A range submits one value per thumb. |
disabled | boolean | Default false | Dimmed, skipped by Tab, and cannot be moved. |
sound | boolean | Default true | Play a tick each time the value moves to another step, if the visitor has sound on. |
className | string | – | Extra classes for the root, merged last. A horizontal slider fills its container; set a width, or a height for a vertical one. |
Motion and sound
Motion
- The thumb follows the pointer directly, with no easing, so it never lags behind the finger.
- While it is dragged the thumb grows to 110% over 150 ms.
- The value bubble fades in and grows from 96% over 150 ms when the thumb is hovered, focused or dragged, and leaves the same way.
- Reduced motion: the thumb does not grow and the bubble appears and leaves at once.
Sound
- A tick each time the value lands on another step, from a drag, a key or a press on the track. A fast drag is rate limited inside the sound engine, so it never buzzes.
Sound is off until the visitor turns it on. Pass sound={false} to keep this component silent. How sound works
Accessibility
- It follows the WAI-ARIA slider pattern. Each thumb holds a native range input, so it has the slider role with its minimum, maximum and current value, and aria-valuetext carries the formatted value.
- Name it with aria-labelledby pointing at a visible label, as the example does, or with an aria-label. In a range the group takes that name and each thumb takes its own from thumbLabels.
- The thumb is 20 pixels across inside a 24 pixel target, and the whole track takes a press: the nearest thumb jumps to it.
- The filled part of the track and the thumb's ring keep 3 to 1 contrast against the page. Tick labels are 12 pixels and keep 4.5 to 1.
- The bubble and the tick labels are hidden from screen readers: the thumb already reports the value.
- In a right-to-left layout the scale runs from right to left and the arrow keys follow it.
- The value bubble is a floating surface. Under a glass material it is translucent, and its tint keeps the text at 4.5 to 1 over any page.
| Keys | Action |
|---|---|
| Tab | Focus the thumb. In a range each thumb is its own tab stop. |
| → / ↑ | Raise the value by one step. |
| ← / ↓ | Lower the value by one step. |
| Shift + arrow / Page Up / Page Down | Move by largeStep, 10 by default. |
| Home / End | Jump to min or max. In a range a thumb stops at the other thumb. |
Source
"use client";
import { useState } from "react";
import { Slider as SliderPrimitive } from "@base-ui/react/slider";
import { cn } from "@/lib/utils";
import { play } from "@/lib/thrum-sound";
export type SliderValue = number | readonly number[];
export type SliderMark = {
/** Where the tick sits, on the slider's own scale. */
value: number;
/** Text under the tick. Leave it out for a bare tick. */
label?: string;
};
export type SliderProps<Value extends SliderValue = SliderValue> = Omit<SliderPrimitive.Root.Props<Value>, "children" | "locale"> & {
/** The locale that prints the value. Fixed by default, so the server and the browser print the same text. */
locale?: string;
/** `true` draws a tick at every step, when there are 50 steps or fewer. A list draws a tick at each value, with its label underneath. */
marks?: boolean | readonly SliderMark[];
/** The value in a bubble over the thumb: `auto` while the thumb is hovered, focused or dragged, `on` always, `off` never. */
valueLabel?: "auto" | "on" | "off";
/** A name for each thumb of a range, in order. Example: `["Lowest price", "Highest price"]`. */
thumbLabels?: readonly string[];
/** Play a tick each time the value moves to another step, if the visitor has sound on. */
sound?: boolean;
};
/** More ticks than this would merge into a bar, so `marks` draws none. */
const MOST_TICKS = 50;
const PILL = "rounded-[calc(var(--radius)*9999)]";
const RANGE_LABELS = ["Minimum", "Maximum"];
/**
* A slider for a value on a scale, or for a range when the value is a list of two numbers.
* Name it with an `aria-label`, or with `aria-labelledby` pointing at its visible label. The thumbs of a range take `thumbLabels`.
*/
export function Slider<Value extends SliderValue = SliderValue>({
locale = "en-US",
marks = false,
valueLabel = "auto",
thumbLabels = RANGE_LABELS,
sound = true,
className,
onValueChange,
onValueCommitted,
...props
}: SliderProps<Value>) {
const [hoveredThumb, setHoveredThumb] = useState<number | null>(null);
const [focusedThumb, setFocusedThumb] = useState<number | null>(null);
const [draggingThumb, setDraggingThumb] = useState<number | null>(null);
const { min = 0, max = 100, step = 1, orientation = "horizontal" } = props;
const vertical = orientation === "vertical";
const start = props.value ?? props.defaultValue;
const thumbs = Array.isArray(start) ? start.length : 1;
const stepCount = Math.round((max - min) / step);
const ticks: readonly SliderMark[] =
marks === true ? (stepCount > 0 && stepCount <= MOST_TICKS ? Array.from({ length: stepCount + 1 }, (_, i) => ({ value: min + i * step })) : []) : marks || [];
const percent = (value: number) => (max === min ? 0 : Math.min(100, Math.max(0, ((value - min) / (max - min)) * 100)));
const labelled = ticks.filter((tick) => tick.label !== undefined);
return (
<SliderPrimitive.Root
data-slot="slider"
locale={locale}
onValueChange={(value, details) => {
if (sound) play("tick");
onValueChange?.(value, details);
}}
onValueCommitted={(value, details) => {
setDraggingThumb(null);
onValueCommitted?.(value, details);
}}
className={cn(
"relative min-w-0 text-foreground select-none data-disabled:opacity-50",
vertical ? "inline-flex h-48" : "w-full",
// An always-on bubble needs room of its own above a horizontal track.
valueLabel === "on" && !vertical && "pt-9",
className,
)}
{...props}
>
{/* The control is padded by half a thumb, so a thumb at either end stays inside the slider's box. */}
<SliderPrimitive.Control
data-slot="slider-control"
className={cn("flex cursor-pointer touch-none items-center justify-center data-disabled:cursor-not-allowed", vertical ? "h-full w-6 flex-col py-2.5" : "h-6 w-full px-2.5")}
>
<SliderPrimitive.Track data-slot="slider-track" className={cn(PILL, "bg-border", vertical ? "h-full w-1.5" : "h-1.5 w-full")}>
<SliderPrimitive.Indicator data-slot="slider-indicator" className={cn(PILL, "bg-primary", vertical ? "w-full" : "h-full")} />
{ticks.map((tick) => (
<span
key={tick.value}
aria-hidden="true"
data-slot="slider-mark"
className={cn("absolute bg-muted-foreground", vertical ? "start-[calc(100%+3px)] h-px w-1 translate-y-1/2" : "top-[calc(100%+3px)] h-1 w-px -translate-x-1/2 rtl:translate-x-1/2")}
style={vertical ? { bottom: `${percent(tick.value)}%` } : { insetInlineStart: `${percent(tick.value)}%` }}
/>
))}
{Array.from({ length: thumbs }, (_, index) => {
const showBubble = valueLabel === "on" || (valueLabel === "auto" && (hoveredThumb === index || focusedThumb === index || draggingThumb === index));
return (
<SliderPrimitive.Thumb
key={index}
index={index}
data-slot="slider-thumb"
data-surface="control"
aria-label={thumbs === 1 ? props["aria-label"] : (thumbLabels[index] ?? `Value ${index + 1}`)}
onPointerEnter={() => setHoveredThumb(index)}
onPointerLeave={() => setHoveredThumb((cur) => (cur === index ? null : cur))}
onFocus={() => setFocusedThumb(index)}
onBlur={() => setFocusedThumb((cur) => (cur === index ? null : cur))}
onPointerDown={() => setDraggingThumb(index)}
onPointerUp={() => setDraggingThumb((cur) => (cur === index ? null : cur))}
onPointerCancel={() => setDraggingThumb((cur) => (cur === index ? null : cur))}
className={cn(
// The pseudo-element makes the 20 pixel thumb a 24 pixel target.
"group/thumb size-5 border-2 border-primary bg-background after:absolute after:-inset-0.5",
PILL,
"transition-[scale] duration-150 ease-out motion-reduce:transition-none data-dragging:scale-110",
"has-focus-visible:outline-2 has-focus-visible:outline-offset-2 has-focus-visible:outline-ring",
)}
>
{valueLabel !== "off" && (
<SliderPrimitive.Value
aria-hidden="true"
data-slot="slider-value"
data-surface={showBubble ? "floating" : undefined}
className={cn(
"pointer-events-none absolute z-10 rounded-md border bg-popover p-2 text-xs leading-none whitespace-nowrap text-popover-foreground tabular-nums shadow-md",
vertical ? "end-full top-1/2 me-2 -translate-y-1/2" : "bottom-full left-1/2 mb-2 -translate-x-1/2",
"transition-[opacity,scale,visibility] duration-150 ease-out motion-reduce:transition-none",
valueLabel === "auto" &&
"invisible scale-[0.96] opacity-0 group-hover/thumb:visible group-hover/thumb:scale-100 group-hover/thumb:opacity-100 group-has-focus-visible/thumb:visible group-has-focus-visible/thumb:scale-100 group-has-focus-visible/thumb:opacity-100 group-data-dragging/thumb:visible group-data-dragging/thumb:scale-100 group-data-dragging/thumb:opacity-100",
)}
>
{(formatted) => formatted[index]}
</SliderPrimitive.Value>
)}
</SliderPrimitive.Thumb>
);
})}
</SliderPrimitive.Track>
</SliderPrimitive.Control>
{labelled.length > 0 && (
<div aria-hidden="true" data-slot="slider-mark-labels" className={cn("relative text-xs text-muted-foreground tabular-nums", vertical ? "my-2.5 ms-1" : "mx-2.5 mt-0.5 h-4")}>
{/* Absolute labels have no width of their own, so a vertical slider keeps an unseen copy of each in the flow to stay as wide as the widest. */}
{vertical &&
labelled.map((tick) => (
<span key={tick.value} className="invisible block h-0 whitespace-nowrap">
{tick.label}
</span>
))}
{labelled.map((tick) => {
const at = percent(tick.value);
return (
<span
key={tick.value}
className={cn(
"absolute leading-4 whitespace-nowrap",
vertical
? "start-0 translate-y-1/2"
: // The first and last labels line up with the slider's edges instead of hanging over them.
at === 0
? "-ms-2.5"
: at === 100
? "ms-2.5 -translate-x-full rtl:translate-x-full"
: "-translate-x-1/2 rtl:translate-x-1/2",
)}
style={vertical ? { bottom: `${at}%` } : { insetInlineStart: `${at}%` }}
>
{tick.label}
</span>
);
})}
</div>
)}
</SliderPrimitive.Root>
);
}Files and dependencies
- Adds
components/ui/slider.tsx- Packages
@base-ui/react@1.9.0- Brings along
- Sound engine
Changelog
- 1.0.0 · 2026-12-03First release.