Get Started
Components
- Accordion
- Attachment
- Avatar
- Badge
- Breadcrumb
- Button
- Button Group
- Card
- Checkbox
- Code Block
- Collapsible
- Dialog
- Dropdown Menu
- Empty
- Field
- Hover Card
- Input
- Input Group
- Input OTP
- Item
- Label
- Marker
- Message
- Number Flow
- Pagination
- Popover
- Progress
- Radio Group
- Select
- Slider
- Sonner
- Spinner
- Switch
- Tooltip
- Separator
- Sheet
- Tabs
- Textarea
- Toggle
- Toggle Group
- Trace
AI Elements
Libraries
Utilities
"use client";
import * as React from "react";
import { cn } from "@/lib/utils";
type SliderOrientation = "horizontal" | "vertical";
interface SliderProps {
"aria-label"?: string;
className?: string;
defaultValue?: number[];
disabled?: boolean;
id?: string;
max?: number;
min?: number;
onValueChange?: (value: number[]) => void;
orientation?: SliderOrientation;
step?: number;
value?: number[];
}
function decimalsFor(step: number): number {
const text = String(step);
const dot = text.indexOf(".");
return dot < 0 ? 0 : text.length - dot - 1;
}
function snapToStep(raw: number, step: number): number {
const decimals = decimalsFor(step);
const factor = 10 ** decimals;
return Math.round(raw * factor) / factor;
}
function clamp(value: number, min: number, max: number): number {
return Math.min(Math.max(value, min), max);
}
function Slider({
"aria-label": ariaLabel,
className,
defaultValue,
disabled = false,
id,
max = 100,
min = 0,
onValueChange,
orientation = "horizontal",
step = 1,
value: valueProp,
}: SliderProps) {
const isControlled = valueProp !== undefined;
const [uncontrolled, setUncontrolled] = React.useState<number[]>(
() => defaultValue ?? [min, max]
);
const values = isControlled ? valueProp : uncontrolled;
const trackRef = React.useRef<HTMLDivElement | null>(null);
const commit = React.useCallback(
(next: number[]) => {
if (!isControlled) {
setUncontrolled(next);
}
onValueChange?.(next);
},
[isControlled, onValueChange]
);
const percentOf = (v: number) => {
const range = Math.max(max - min, Number.EPSILON);
return ((v - min) / range) * 100;
};
const valueFromPointer = (clientX: number, clientY: number): number => {
const track = trackRef.current;
if (!track) {
return min;
}
const rect = track.getBoundingClientRect();
let ratio: number;
if (orientation === "horizontal") {
ratio = rect.width === 0 ? 0 : (clientX - rect.left) / rect.width;
} else {
ratio = rect.height === 0 ? 0 : 1 - (clientY - rect.top) / rect.height;
}
ratio = clamp(ratio, 0, 1);
return snapToStep(min + ratio * (max - min), step);
};
const boundsFor = (index: number): [number, number] => {
const lower = index === 0 ? min : values[index - 1];
const upper = index === values.length - 1 ? max : values[index + 1];
return [lower, upper];
};
const updateThumb = (index: number, raw: number) => {
const [lo, hi] = boundsFor(index);
const next = values.slice();
next[index] = clamp(raw, lo, hi);
if (next[index] !== values[index]) {
commit(next);
}
};
const handlePointerDown =
(index: number) => (event: React.PointerEvent<HTMLSpanElement>) => {
if (disabled) {
return;
}
event.preventDefault();
event.stopPropagation();
const target = event.currentTarget;
try {
target.setPointerCapture(event.pointerId);
} catch {
// noop
}
updateThumb(index, valueFromPointer(event.clientX, event.clientY));
const onMove = (ev: PointerEvent) => {
updateThumb(index, valueFromPointer(ev.clientX, ev.clientY));
};
const onUp = () => {
target.removeEventListener("pointermove", onMove);
target.removeEventListener("pointerup", onUp);
target.removeEventListener("pointercancel", onUp);
};
target.addEventListener("pointermove", onMove);
target.addEventListener("pointerup", onUp);
target.addEventListener("pointercancel", onUp);
};
const handleKeyDown =
(index: number) => (event: React.KeyboardEvent<HTMLSpanElement>) => {
if (disabled) {
return;
}
const [lo, hi] = boundsFor(index);
const current = values[index];
let next = current;
switch (event.key) {
case "ArrowRight":
case "ArrowUp":
next = clamp(snapToStep(current + step, step), lo, hi);
break;
case "ArrowLeft":
case "ArrowDown":
next = clamp(snapToStep(current - step, step), lo, hi);
break;
case "Home":
next = lo;
break;
case "End":
next = hi;
break;
case "PageUp":
next = clamp(snapToStep(current + step * 10, step), lo, hi);
break;
case "PageDown":
next = clamp(snapToStep(current - step * 10, step), lo, hi);
break;
default:
return;
}
event.preventDefault();
if (next !== current) {
const arr = values.slice();
arr[index] = next;
commit(arr);
}
};
const rangeStart = percentOf(values[0]);
const rangeEnd = percentOf(values.at(-1) ?? min);
const rangeStyle: React.CSSProperties =
orientation === "horizontal"
? { left: `${rangeStart}%`, right: `${100 - rangeEnd}%` }
: { bottom: `${rangeStart}%`, top: `${100 - rangeEnd}%` };
return (
<div
className={cn(
"relative flex w-full touch-none select-none",
orientation === "horizontal"
? "items-center"
: "h-full min-h-40 flex-col items-center",
disabled ? "opacity-50" : undefined,
className
)}
data-disabled={disabled || undefined}
data-orientation={orientation}
data-slot="slider"
id={id}
>
<div
className={cn(
"bg-muted relative grow overflow-hidden rounded-full",
orientation === "horizontal" ? "h-1 w-full" : "h-full w-1"
)}
data-slot="slider-track"
ref={trackRef}
>
<div
className={cn(
"bg-primary absolute select-none",
orientation === "horizontal" ? "inset-y-0" : "inset-x-0"
)}
data-slot="slider-range"
style={rangeStyle}
/>
</div>
{values.map((v, index) => {
const percent = percentOf(v);
const thumbStyle: React.CSSProperties =
orientation === "horizontal"
? {
left: `${percent}%`,
top: "50%",
transform: "translate(-50%, -50%)",
}
: {
bottom: `${percent}%`,
left: "50%",
transform: "translate(-50%, 50%)",
};
return (
<span
aria-disabled={disabled || undefined}
aria-label={ariaLabel}
aria-orientation={orientation}
aria-valuemax={max}
aria-valuemin={min}
aria-valuenow={v}
className={cn(
"border-primary bg-background ring-ring/50 absolute block size-3.5 shrink-0 rounded-full border shadow-sm transition-[color,box-shadow] select-none",
"after:absolute after:-inset-2",
"hover:ring-3 focus-visible:ring-3 focus-visible:outline-hidden active:ring-3",
disabled ? "pointer-events-none opacity-50" : "cursor-grab"
)}
data-slot="slider-thumb"
key={`slider-thumb-${index}`}
onKeyDown={handleKeyDown(index)}
onPointerDown={handlePointerDown(index)}
role="slider"
style={thumbStyle}
tabIndex={disabled ? -1 : 0}
/>
);
})}
</div>
);
}
export { Slider };Slider lets the user pick a value or range from a track. It supports single values, ranges, multiple thumbs, and vertical orientation.
Installation
$ bunx --bun frakment add slider$ npx frakment add slider$ pnpm dlx frakment add slider$ yarn dlx frakment add slider
Copy and paste the following code into your project.
"use client";
import * as React from "react";
import { cn } from "@/lib/utils";
type SliderOrientation = "horizontal" | "vertical";
interface SliderProps {
"aria-label"?: string;
className?: string;
defaultValue?: number[];
disabled?: boolean;
id?: string;
max?: number;
min?: number;
onValueChange?: (value: number[]) => void;
orientation?: SliderOrientation;
step?: number;
value?: number[];
}
function decimalsFor(step: number): number {
const text = String(step);
const dot = text.indexOf(".");
return dot < 0 ? 0 : text.length - dot - 1;
}
function snapToStep(raw: number, step: number): number {
const decimals = decimalsFor(step);
const factor = 10 ** decimals;
return Math.round(raw * factor) / factor;
}
function clamp(value: number, min: number, max: number): number {
return Math.min(Math.max(value, min), max);
}
function Slider({
"aria-label": ariaLabel,
className,
defaultValue,
disabled = false,
id,
max = 100,
min = 0,
onValueChange,
orientation = "horizontal",
step = 1,
value: valueProp,
}: SliderProps) {
const isControlled = valueProp !== undefined;
const [uncontrolled, setUncontrolled] = React.useState<number[]>(
() => defaultValue ?? [min, max]
);
const values = isControlled ? valueProp : uncontrolled;
const trackRef = React.useRef<HTMLDivElement | null>(null);
const commit = React.useCallback(
(next: number[]) => {
if (!isControlled) {
setUncontrolled(next);
}
onValueChange?.(next);
},
[isControlled, onValueChange]
);
const percentOf = (v: number) => {
const range = Math.max(max - min, Number.EPSILON);
return ((v - min) / range) * 100;
};
const valueFromPointer = (clientX: number, clientY: number): number => {
const track = trackRef.current;
if (!track) {
return min;
}
const rect = track.getBoundingClientRect();
let ratio: number;
if (orientation === "horizontal") {
ratio = rect.width === 0 ? 0 : (clientX - rect.left) / rect.width;
} else {
ratio = rect.height === 0 ? 0 : 1 - (clientY - rect.top) / rect.height;
}
ratio = clamp(ratio, 0, 1);
return snapToStep(min + ratio * (max - min), step);
};
const boundsFor = (index: number): [number, number] => {
const lower = index === 0 ? min : values[index - 1];
const upper = index === values.length - 1 ? max : values[index + 1];
return [lower, upper];
};
const updateThumb = (index: number, raw: number) => {
const [lo, hi] = boundsFor(index);
const next = values.slice();
next[index] = clamp(raw, lo, hi);
if (next[index] !== values[index]) {
commit(next);
}
};
const handlePointerDown =
(index: number) => (event: React.PointerEvent<HTMLSpanElement>) => {
if (disabled) {
return;
}
event.preventDefault();
event.stopPropagation();
const target = event.currentTarget;
try {
target.setPointerCapture(event.pointerId);
} catch {
// noop
}
updateThumb(index, valueFromPointer(event.clientX, event.clientY));
const onMove = (ev: PointerEvent) => {
updateThumb(index, valueFromPointer(ev.clientX, ev.clientY));
};
const onUp = () => {
target.removeEventListener("pointermove", onMove);
target.removeEventListener("pointerup", onUp);
target.removeEventListener("pointercancel", onUp);
};
target.addEventListener("pointermove", onMove);
target.addEventListener("pointerup", onUp);
target.addEventListener("pointercancel", onUp);
};
const handleKeyDown =
(index: number) => (event: React.KeyboardEvent<HTMLSpanElement>) => {
if (disabled) {
return;
}
const [lo, hi] = boundsFor(index);
const current = values[index];
let next = current;
switch (event.key) {
case "ArrowRight":
case "ArrowUp":
next = clamp(snapToStep(current + step, step), lo, hi);
break;
case "ArrowLeft":
case "ArrowDown":
next = clamp(snapToStep(current - step, step), lo, hi);
break;
case "Home":
next = lo;
break;
case "End":
next = hi;
break;
case "PageUp":
next = clamp(snapToStep(current + step * 10, step), lo, hi);
break;
case "PageDown":
next = clamp(snapToStep(current - step * 10, step), lo, hi);
break;
default:
return;
}
event.preventDefault();
if (next !== current) {
const arr = values.slice();
arr[index] = next;
commit(arr);
}
};
const rangeStart = percentOf(values[0]);
const rangeEnd = percentOf(values.at(-1) ?? min);
const rangeStyle: React.CSSProperties =
orientation === "horizontal"
? { left: `${rangeStart}%`, right: `${100 - rangeEnd}%` }
: { bottom: `${rangeStart}%`, top: `${100 - rangeEnd}%` };
return (
<div
className={cn(
"relative flex w-full touch-none select-none",
orientation === "horizontal"
? "items-center"
: "h-full min-h-40 flex-col items-center",
disabled ? "opacity-50" : undefined,
className
)}
data-disabled={disabled || undefined}
data-orientation={orientation}
data-slot="slider"
id={id}
>
<div
className={cn(
"bg-muted relative grow overflow-hidden rounded-full",
orientation === "horizontal" ? "h-1 w-full" : "h-full w-1"
)}
data-slot="slider-track"
ref={trackRef}
>
<div
className={cn(
"bg-primary absolute select-none",
orientation === "horizontal" ? "inset-y-0" : "inset-x-0"
)}
data-slot="slider-range"
style={rangeStyle}
/>
</div>
{values.map((v, index) => {
const percent = percentOf(v);
const thumbStyle: React.CSSProperties =
orientation === "horizontal"
? {
left: `${percent}%`,
top: "50%",
transform: "translate(-50%, -50%)",
}
: {
bottom: `${percent}%`,
left: "50%",
transform: "translate(-50%, 50%)",
};
return (
<span
aria-disabled={disabled || undefined}
aria-label={ariaLabel}
aria-orientation={orientation}
aria-valuemax={max}
aria-valuemin={min}
aria-valuenow={v}
className={cn(
"border-primary bg-background ring-ring/50 absolute block size-3.5 shrink-0 rounded-full border shadow-sm transition-[color,box-shadow] select-none",
"after:absolute after:-inset-2",
"hover:ring-3 focus-visible:ring-3 focus-visible:outline-hidden active:ring-3",
disabled ? "pointer-events-none opacity-50" : "cursor-grab"
)}
data-slot="slider-thumb"
key={`slider-thumb-${index}`}
onKeyDown={handleKeyDown(index)}
onPointerDown={handlePointerDown(index)}
role="slider"
style={thumbStyle}
tabIndex={disabled ? -1 : 0}
/>
);
})}
</div>
);
}
export { Slider };Update the import paths to match your project setup.
Usage
import { Slider } from "@/components/ui/slider";<Slider defaultValue={[75]} max={100} step={1} />Examples
Range
Pass two values to select a range.
import { Slider } from "@/components/ui/slider";
export function SliderRange() {
return (
<Slider
className="mx-auto w-full max-w-xs"
defaultValue={[25, 50]}
max={100}
step={5}
/>
);
}Multiple thumbs
import { Slider } from "@/components/ui/slider";
export function SliderMultiple() {
return (
<Slider
className="mx-auto w-full max-w-xs"
defaultValue={[10, 20, 70]}
max={100}
step={10}
/>
);
}Vertical
import { Slider } from "@/components/ui/slider";
export function SliderVertical() {
return (
<div className="mx-auto flex w-full max-w-xs items-center justify-center gap-4">
<Slider
className="h-40"
defaultValue={[50]}
max={100}
orientation="vertical"
step={1}
/>
<Slider
className="h-40"
defaultValue={[25]}
max={100}
orientation="vertical"
step={1}
/>
</div>
);
}Controlled
0.3, 0.7
"use client";
import * as React from "react";
import { Label } from "@/components/ui/label";
import { Slider } from "@/components/ui/slider";
export function SliderControlled() {
const [value, setValue] = React.useState([0.3, 0.7]);
return (
<div className="mx-auto grid w-full max-w-xs gap-3">
<div className="flex items-center justify-between gap-2">
<Label htmlFor="slider-demo-temperature">Temperature</Label>
<span className="text-muted-foreground text-sm">
{value.join(", ")}
</span>
</div>
<Slider
id="slider-demo-temperature"
max={1}
min={0}
onValueChange={(value) => setValue(value as number[])}
step={0.1}
value={value}
/>
</div>
);
}Disabled
import { Slider } from "@/components/ui/slider";
export function SliderDisabled() {
return (
<Slider
className="mx-auto w-full max-w-xs"
defaultValue={[50]}
disabled
max={100}
step={1}
/>
);
}In Context
Settings panel
Volume75
Brightness60
"use client";
import * as React from "react";
import { Slider } from "@/components/ui/slider";
export function SliderSettingsPanel() {
const [volume, setVolume] = React.useState(75);
const [brightness, setBrightness] = React.useState(60);
return (
<div className="border-border mx-auto w-full max-w-sm space-y-6 rounded-lg border p-4">
<div className="grid gap-2">
<div className="flex items-center justify-between text-sm">
<span className="font-medium">Volume</span>
<span className="text-muted-foreground tabular-nums">{volume}</span>
</div>
<Slider
defaultValue={[75]}
max={100}
onValueChange={(value) => setVolume(value[0])}
step={1}
/>
</div>
<div className="grid gap-2">
<div className="flex items-center justify-between text-sm">
<span className="font-medium">Brightness</span>
<span className="text-muted-foreground tabular-nums">
{brightness}
</span>
</div>
<Slider
defaultValue={[60]}
max={100}
onValueChange={(value) => setBrightness(value[0])}
step={1}
/>
</div>
</div>
);
}Price filter
Price range$25 – $75
"use client";
import * as React from "react";
import { Slider } from "@/components/ui/slider";
export function SliderPriceFilter() {
const [range, setRange] = React.useState([25, 75]);
return (
<div className="border-border mx-auto w-full max-w-sm rounded-lg border p-4">
<div className="mb-3 flex items-center justify-between text-sm">
<span className="font-medium">Price range</span>
<span className="text-muted-foreground tabular-nums">
${range[0]} – ${range[1]}
</span>
</div>
<Slider
defaultValue={[25, 75]}
max={100}
onValueChange={setRange}
step={5}
/>
</div>
);
}API Reference
Slider
| Prop | Type | Default | Description |
|---|---|---|---|
value | number[] | — | Controlled values, one per thumb. |
defaultValue | number[] | — | Uncontrolled initial values. |
onValueChange | (value: number[]) => void | — | Fires on every drag and keypress. |
min | number | — | Lower bound of the range. |
max | number | — | Upper bound of the range. |
step | number | — | Increment between selectable values. |
orientation | horizontalvertical | — | Layout direction. |
disabled | boolean | — | Disables the slider and every thumb. |
aria-label | string | — | Accessible name applied to every thumb. |
Anatomy
<Slider defaultValue={[50]} max={100} step={1} />- Root — flex container, horizontal or vertical
- Track — muted rail behind the fill
- Range — filled portion between min and the current value(s)
- Thumb — draggable handle, one per value
States
| State | How |
|---|---|
| Single | defaultValue={[50]} |
| Range | defaultValue={[25, 75]} |
| Multi | defaultValue={[10, 20, 70]} |
| Vertical | orientation="vertical" |
| Disabled | disabled prop |
Keyboard
| Key | Action |
|---|---|
← / → | Decrease / increase value |
↑ / ↓ | Decrease / increase value |
Home / End | Min / max |
Page Up / Page Down | Step × 10 up / down |
Data Attributes
| Attribute | Values |
|---|---|
data-slot | slider, slider-track, slider-range, slider-thumb |
data-orientation | horizontal | vertical |
data-disabled | true |
Accessibility
- Every thumb renders
role="slider"witharia-valuemin,aria-valuemax, andaria-valuenow. - Each thumb is keyboard focusable and responds to arrow keys, Home, End, Page Up, and Page Down.
aria-orientationis set on each thumb.- Pair the slider with a
Labelwhen the slider is not self-describing.
Best Practices
- Show the current value. A slider without a visible number or label is hard to read. Pair it with a formatted span.
- Prefer ranges when both ends matter. Use two thumbs for temperature, price, or scale intervals.
- Add a label. Link a
LabelwithhtmlForto the slideridso screen readers announce it. - Do not replace a numeric input. Sliders are imprecise for exact values. Pair with a number input when precision matters.