Slider
The shadcn/ui Slider with a thumb that grows slightly while you drag it and range-slider labels for screen readers — plus two animated React slider blocks built with Motion and Radix: a slider with a floating value tooltip that leans slightly as you drag, and a stepped slider with tick marks that light up.
- Drop-in shadcn API
- Range & vertical
- Keyboard accessible
- Motion blocks
"use client";
import * as React from "react";
import { ValueSlider } from "@/components/dusk/slider/value-slider";
const currency = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", maximumFractionDigits: 0 });
export default function ValueSliderDemo() {
const [budget, setBudget] = React.useState([240, 720]);
return (
<div className="flex w-full max-w-sm flex-col gap-12 pt-8">
<ValueSlider defaultValue={[42]} aria-label="Opacity" formatValue={(v) => `${v}%`} />
<ValueSlider
value={budget}
onValueChange={setBudget}
min={0}
max={1000}
step={10}
minStepsBetweenThumbs={5}
aria-label="Budget"
formatValue={(v) => currency.format(v)}
/>
</div>
);
}Installation
$ npx shadcn@latest add https://duskui.com/r/slider.json1. Install the dependencies.
npm install @radix-ui/react-slider2. Copy the source into
components/ui/slider.tsx.slider.tsx "use client" import * as React from "react" import * as SliderPrimitive from "@radix-ui/react-slider" import { cn } from "@/lib/utils" /** * DuskUI Slider — a drop-in upgrade of the shadcn/ui Slider. * * Same API as shadcn: pass one value for a single thumb or several for a * range (`defaultValue={[20, 80]}`), horizontal or vertical. Plus: * - The thumb you're dragging grows a little and fills in, so it's clear which one moves. * - A solid range fill; the track lightens slightly on hover. * - A clear focus-visible ring for keyboard users (arrows, Page Up/Down, Home/End). * - Under `prefers-reduced-motion` sizes change instantly. * - `aria-label` / `aria-labelledby` on the Slider are forwarded to the thumbs * (range thumbs are suffixed "minimum" / "maximum"). * CSS only (no Motion). The root gets `data-dragging` while a pointer is down. */ function Slider({ className, defaultValue, value, min = 0, max = 100, onPointerDown, onPointerUp, onPointerCancel, onLostPointerCapture, "aria-label": ariaLabel, "aria-labelledby": ariaLabelledBy, ...props }: React.ComponentProps<typeof SliderPrimitive.Root>) { const [dragging, setDragging] = React.useState(false) // One thumb per value. With no value at all, render a single thumb at `min`. const thumbCount = (Array.isArray(value) ? value : Array.isArray(defaultValue) ? defaultValue : [min]).length const rangeNames = thumbCount === 2 ? ["minimum", "maximum"] : undefined // The root is a plain span, so its label is moved onto each thumb (role="slider"). const thumbLabel = (index: number) => { if (!ariaLabel) return undefined if (thumbCount === 1) return ariaLabel return `${ariaLabel}, ${rangeNames?.[index] ?? `value ${index + 1} of ${thumbCount}`}` } return ( <SliderPrimitive.Root data-slot="slider" data-dragging={dragging || undefined} defaultValue={defaultValue} value={value} min={min} max={max} className={cn( "group/slider relative flex w-full touch-none items-center select-none", "data-[disabled]:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col", className )} onPointerDown={(event) => { onPointerDown?.(event) if (!props.disabled && event.button === 0) setDragging(true) }} onPointerUp={(event) => { onPointerUp?.(event) setDragging(false) }} onPointerCancel={(event) => { onPointerCancel?.(event) setDragging(false) }} onLostPointerCapture={(event) => { onLostPointerCapture?.(event) setDragging(false) }} {...props} > <SliderPrimitive.Track data-slot="slider-track" className={cn( "relative grow overflow-hidden rounded-full bg-muted transition-colors duration-150 group-hover/slider:bg-secondary", "data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5" )} > <SliderPrimitive.Range data-slot="slider-range" className={cn( "absolute rounded-full bg-primary", "data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full" )} /> </SliderPrimitive.Track> {Array.from({ length: thumbCount }, (_, index) => ( <SliderPrimitive.Thumb data-slot="slider-thumb" key={index} aria-label={thumbLabel(index)} aria-labelledby={thumbCount === 1 ? ariaLabelledBy : undefined} className={cn( "block size-4 shrink-0 rounded-full border-2 border-primary bg-background outline-none", "shadow-sm transition-[scale,box-shadow,background-color] duration-150 ease-out", // The thumb being dragged is the focused one: Radix focuses it on pointer down. "group-data-[dragging]/slider:focus:scale-110 group-data-[dragging]/slider:focus:bg-primary", "focus-visible:ring-[3px] focus-visible:ring-ring/50", "data-[disabled]:pointer-events-none", "motion-reduce:transition-none" )} /> ))} </SliderPrimitive.Root> ) } export { Slider }
Replaces components/ui/slider.tsx with the same API. The drag feedback is CSS, so the base needs no Motion; the root gets data-dragging while a pointer is down if you want to style around it.
Usage
import { Slider } from "@/components/ui/slider"
export function Volume() {
return <Slider defaultValue={[60]} max={100} step={1} aria-label="Volume" />
}Examples
Default
Press and drag a thumb and it grows a little to show it's held. Arrow keys, Page Up/Down and Home/End work once it's focused.
"use client";
import * as React from "react";
import { Volume1, Volume2 } from "lucide-react";
import { Slider } from "@/components/ui/slider";
export default function SliderBasicDemo() {
const [volume, setVolume] = React.useState([60]);
return (
<div className="flex w-full max-w-sm flex-col gap-3">
<div className="flex items-center justify-between text-sm">
<span id="volume-label" className="font-medium">Volume</span>
<span className="text-muted-foreground tabular-nums">{volume[0]}%</span>
</div>
<div className="flex items-center gap-3 text-muted-foreground">
<Volume1 className="size-4 shrink-0" aria-hidden />
<Slider value={volume} onValueChange={setVolume} max={100} step={1} aria-labelledby="volume-label" />
<Volume2 className="size-4 shrink-0" aria-hidden />
</div>
</div>
);
}Range & vertical
Pass two values for a range; minStepsBetweenThumbs keeps the thumbs apart and they're announced as “Price, minimum” and “Price, maximum”. Set orientation="vertical" and give it a height for a vertical slider.
"use client";
import * as React from "react";
import { Slider } from "@/components/ui/slider";
export default function SliderRangeDemo() {
const [range, setRange] = React.useState([25, 75]);
return (
<div className="flex w-full max-w-md items-center gap-10">
<div className="flex flex-1 flex-col gap-3">
<div className="flex items-center justify-between text-sm">
<span className="font-medium">Price</span>
<span className="text-muted-foreground tabular-nums">
${range[0]} – ${range[1]}
</span>
</div>
<Slider value={range} onValueChange={setRange} max={100} step={5} minStepsBetweenThumbs={1} aria-label="Price" />
</div>
<Slider defaultValue={[40]} orientation="vertical" aria-label="Brightness" className="h-32" />
</div>
);
}Blocks
Ready-made variations composed from the base component with Motion. Each installs on its own and pulls in its dependencies automatically.
Value Slider
A value bubble rides on each thumb. It springs up on hover, keyboard focus or drag, leans into the direction you're dragging (driven by the value's velocity, so nothing re-renders per frame) and settles upright when you stop. Format it with formatValue; the same text is announced via aria-valuetext.
"use client";
import * as React from "react";
import { ValueSlider } from "@/components/dusk/slider/value-slider";
const currency = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", maximumFractionDigits: 0 });
export default function ValueSliderDemo() {
const [budget, setBudget] = React.useState([240, 720]);
return (
<div className="flex w-full max-w-sm flex-col gap-12 pt-8">
<ValueSlider defaultValue={[42]} aria-label="Opacity" formatValue={(v) => `${v}%`} />
<ValueSlider
value={budget}
onValueChange={setBudget}
min={0}
max={1000}
step={10}
minStepsBetweenThumbs={5}
aria-label="Budget"
formatValue={(v) => currency.format(v)}
/>
</div>
);
}$ npx shadcn@latest add https://duskui.com/r/value-slider.json1. Install the dependencies.
npm install motion @radix-ui/react-slider2. Copy the source into
components/dusk/slider/value-slider.tsx.value-slider.tsx "use client"; import * as React from "react"; import * as SliderPrimitive from "@radix-ui/react-slider"; import { AnimatePresence, motion, useMotionValue, useReducedMotion, useSpring, useTransform, useVelocity, } from "motion/react"; import { cn } from "@/lib/utils"; export interface ValueSliderProps extends Omit<React.ComponentProps<typeof SliderPrimitive.Root>, "value" | "defaultValue" | "onValueChange"> { value?: number[]; defaultValue?: number[]; onValueChange?: (value: number[]) => void; /** Formats the number in the bubble and the screen-reader value text. */ formatValue?: (value: number) => string; /** When the bubble is visible: while interacting (hover, focus, drag) or always. */ showBubble?: "interacting" | "always"; /** Accessible name. Range thumbs get “minimum” / “maximum” appended. */ "aria-label"?: string; } const defaultFormat = (value: number) => String(value); type ThumbProps = { value: number; index: number; count: number; range: number; visible: boolean; label?: string; format: (value: number) => string; dragging: boolean; onFocusChange: (index: number, focused: boolean) => void; }; function ValueThumb({ value, index, count, range, visible, label, format, dragging, onFocusChange }: ThumbProps) { const reduceMotion = useReducedMotion() ?? false; // The value as a motion value, so its velocity can tilt the bubble without re-rendering. const position = useMotionValue(value); React.useEffect(() => { position.set(value); }, [position, value]); const velocity = useVelocity(position); // Moving right makes the bubble lean left, like it's being dragged along. const lean = useTransform(velocity, (v) => { if (reduceMotion || range <= 0) return 0; return Math.max(-8, Math.min(8, (-v / range) * 6)); }); const rotate = useSpring(lean, { stiffness: 300, damping: 28 }); const names = count === 2 ? ["minimum", "maximum"] : undefined; const thumbLabel = label ? count === 1 ? label : `${label}, ${names?.[index] ?? `value ${index + 1} of ${count}`}` : undefined; return ( <SliderPrimitive.Thumb aria-label={thumbLabel} aria-valuetext={format(value)} // Show the bubble for keyboard focus only; Radix focuses thumbs without // focus-visible on pointer down, and dragging is handled separately. onFocus={(event) => onFocusChange(index, event.currentTarget.matches(":focus-visible"))} onKeyDown={() => onFocusChange(index, true)} onBlur={() => onFocusChange(index, false)} className={cn( "group/thumb relative block size-5 rounded-full outline-none", "focus-visible:ring-[3px] focus-visible:ring-ring/50 data-[disabled]:pointer-events-none" )} > {/* The visible knob scales on its own so the bubble keeps its size. */} <span aria-hidden className={cn( "pointer-events-none absolute inset-0 rounded-full border-2 border-primary bg-background shadow-sm", "transition-[scale,background-color] duration-150 ease-out motion-reduce:transition-none", dragging && "group-focus/thumb:scale-110" )} /> <AnimatePresence> {visible && ( <span key="bubble" aria-hidden className="pointer-events-none absolute bottom-full left-1/2 mb-3 -translate-x-1/2"> <motion.span className="relative flex origin-bottom flex-col items-center" style={{ rotate }} initial={reduceMotion ? { opacity: 0 } : { opacity: 0, y: 4, scale: 0.96 }} animate={{ opacity: 1, y: 0, scale: 1 }} exit={reduceMotion ? { opacity: 0 } : { opacity: 0, y: 4, scale: 0.96, transition: { duration: 0.12 } }} transition={reduceMotion ? { duration: 0.15 } : { type: "spring", duration: 0.25, bounce: 0.1 }} > <span className="min-w-9 rounded-md bg-foreground px-2 py-1 text-center text-xs font-medium whitespace-nowrap text-background tabular-nums shadow-md"> {format(value)} </span> <span className="-mt-1 size-2 rotate-45 rounded-[1px] bg-foreground" /> </motion.span> </span> )} </AnimatePresence> </SliderPrimitive.Thumb> ); } /** * A slider with a value bubble riding on each thumb. The bubble appears on * hover, focus or drag, leans slightly into the direction you're dragging (driven by * the value's velocity, so it never re-renders per frame) and settles upright * when you stop. Works for single values and ranges, and announces the * formatted value via aria-valuetext. No lean and a plain fade under reduced motion. */ export function ValueSlider({ value: valueProp, defaultValue, onValueChange, min = 0, max = 100, formatValue = defaultFormat, showBubble = "interacting", className, disabled, "aria-label": ariaLabel, onPointerEnter, onPointerLeave, onPointerDown, onPointerUp, onLostPointerCapture, ...props }: ValueSliderProps) { const [internal, setInternal] = React.useState<number[]>(defaultValue ?? [min]); const values = valueProp ?? internal; const [hovered, setHovered] = React.useState(false); const [dragging, setDragging] = React.useState(false); const [focused, setFocused] = React.useState<number[]>([]); const handleChange = (next: number[]) => { if (valueProp === undefined) setInternal(next); onValueChange?.(next); }; const handleFocus = React.useCallback((index: number, isFocused: boolean) => { setFocused((current) => isFocused ? (current.includes(index) ? current : [...current, index]) : current.filter((i) => i !== index) ); }, []); const interacting = hovered || dragging; return ( <SliderPrimitive.Root value={values} onValueChange={handleChange} min={min} max={max} disabled={disabled} data-dragging={dragging || undefined} className={cn( "relative flex w-full touch-none items-center py-2 select-none data-[disabled]:opacity-50", className )} onPointerEnter={(event) => { onPointerEnter?.(event); if (event.pointerType === "mouse") setHovered(true); }} onPointerLeave={(event) => { onPointerLeave?.(event); setHovered(false); }} onPointerDown={(event) => { onPointerDown?.(event); if (!disabled && event.button === 0) setDragging(true); }} onPointerUp={(event) => { onPointerUp?.(event); setDragging(false); }} onLostPointerCapture={(event) => { onLostPointerCapture?.(event); setDragging(false); }} {...props} > <SliderPrimitive.Track className="relative h-1.5 w-full grow overflow-hidden rounded-full bg-muted"> <SliderPrimitive.Range className="absolute h-full rounded-full bg-primary" /> </SliderPrimitive.Track> {values.map((v, index) => ( <ValueThumb key={index} value={v} index={index} count={values.length} range={max - min} label={ariaLabel} format={formatValue} dragging={dragging} visible={!disabled && (showBubble === "always" || interacting || focused.includes(index))} onFocusChange={handleFocus} /> ))} </SliderPrimitive.Root> ); }
| Prop | Type | Default | Description |
|---|---|---|---|
| value / defaultValue | number[] | — | One value for a single thumb, two for a range. |
| onValueChange | (value: number[]) => void | — | Called on every change. |
| formatValue | (value: number) => string | — | Text in the bubble and for screen readers. |
| showBubble | "interacting" | "always" | "interacting" | Show the bubble only on hover, focus and drag, or all the time. |
| aria-label | string | — | Accessible name; range thumbs get minimum / maximum appended. |
| ...props | Radix Slider props | — | min, max, step, minStepsBetweenThumbs, disabled, onValueCommit… |
Stepped Slider
A slider that snaps between named steps — plans, sizes, levels. Tick marks light up as the range passes them, the selected tick stretches, and clicking a label jumps to it. Values are strings, and name submits the selected step with a form.
Monthly requests
Billed monthly, cancel any time.
$49/mo
"use client";
import * as React from "react";
import { SteppedSlider } from "@/components/dusk/slider/stepped-slider";
const plans = [
{ value: "1k", label: "1K", valueText: "1,000 requests" },
{ value: "10k", label: "10K", valueText: "10,000 requests" },
{ value: "50k", label: "50K", valueText: "50,000 requests" },
{ value: "100k", label: "100K", valueText: "100,000 requests" },
{ value: "500k", label: "500K", valueText: "500,000 requests" },
{ value: "1m", label: "1M", valueText: "1 million requests" },
];
const prices: Record<string, number> = { "1k": 0, "10k": 19, "50k": 49, "100k": 89, "500k": 249, "1m": 399 };
export default function SteppedSliderDemo() {
const [plan, setPlan] = React.useState("50k");
return (
<div className="flex w-full max-w-sm flex-col gap-6">
<div className="flex items-end justify-between">
<div>
<p id="requests-label" className="text-sm font-medium">Monthly requests</p>
<p className="text-xs text-muted-foreground">Billed monthly, cancel any time.</p>
</div>
<p className="text-2xl font-semibold tracking-tight tabular-nums">
${prices[plan]}
<span className="text-sm font-normal text-muted-foreground">/mo</span>
</p>
</div>
<SteppedSlider steps={plans} value={plan} onValueChange={setPlan} aria-label="Monthly requests" />
<SteppedSlider steps={["XS", "S", "M", "L", "XL"]} defaultValue="M" aria-label="T-shirt size" />
</div>
);
}$ npx shadcn@latest add https://duskui.com/r/stepped-slider.json1. Install the dependencies.
npm install motion @radix-ui/react-slider2. Copy the source into
components/dusk/slider/stepped-slider.tsx.stepped-slider.tsx "use client"; import * as React from "react"; import * as SliderPrimitive from "@radix-ui/react-slider"; import { motion, useReducedMotion } from "motion/react"; import { cn } from "@/lib/utils"; export type SteppedSliderStep = string | { value: string; label: React.ReactNode; valueText?: string }; export interface SteppedSliderProps extends Omit< React.ComponentProps<typeof SliderPrimitive.Root>, "value" | "defaultValue" | "onValueChange" | "onValueCommit" | "min" | "max" | "step" | "name" | "inverted" | "minStepsBetweenThumbs" | "orientation" > { /** The choices, in order. Strings are both the value and the label. */ steps: SteppedSliderStep[]; /** The selected step's value. */ value?: string; defaultValue?: string; onValueChange?: (value: string) => void; /** Fires when the user finishes changing the value (pointer up or key press). */ onValueCommit?: (value: string) => void; /** Submits the selected step's value with a form. */ name?: string; /** Hide the labels under the ticks. */ hideLabels?: boolean; /** Accessible name for the slider. */ "aria-label"?: string; } function normalize(step: SteppedSliderStep) { return typeof step === "string" ? { value: step, label: step as React.ReactNode, valueText: step } : { ...step, valueText: step.valueText ?? (typeof step.label === "string" ? step.label : step.value) }; } /** * A slider that snaps between named steps (sizes, plans, levels). Tick marks * light up as the range passes them, the selected tick stretches, * and clicking a label jumps to it. Works with arrows, Home/End and Page keys, * announces the step's label via aria-valuetext and can submit the step's * value in a form. Ticks change instantly under reduced motion. */ export function SteppedSlider({ steps, value: valueProp, defaultValue, onValueChange, onValueCommit, name, hideLabels = false, disabled, className, "aria-label": ariaLabel, onPointerDown, onPointerUp, onLostPointerCapture, ...props }: SteppedSliderProps) { const reduceMotion = useReducedMotion() ?? false; const [dragging, setDragging] = React.useState(false); const items = React.useMemo(() => steps.map(normalize), [steps]); const [internal, setInternal] = React.useState(defaultValue ?? items[0]?.value); const selected = valueProp ?? internal; const index = Math.max(0, items.findIndex((item) => item.value === selected)); const last = Math.max(1, items.length - 1); const toValue = (i: number) => items[Math.min(items.length - 1, Math.max(0, i))]?.value ?? ""; return ( <div className={cn("w-full", !hideLabels ? "pb-9" : "pb-3", className)}> <SliderPrimitive.Root value={[index]} min={0} max={last} step={1} disabled={disabled} onValueChange={([i]) => { const next = toValue(i); if (valueProp === undefined) setInternal(next); onValueChange?.(next); }} onValueCommit={([i]) => onValueCommit?.(toValue(i))} data-dragging={dragging || undefined} onPointerDown={(event) => { onPointerDown?.(event); if (!disabled && event.button === 0) setDragging(true); }} onPointerUp={(event) => { onPointerUp?.(event); setDragging(false); }} onLostPointerCapture={(event) => { onLostPointerCapture?.(event); setDragging(false); }} className="group/slider relative flex h-5 w-full touch-none items-center select-none data-[disabled]:opacity-50" {...props} > <SliderPrimitive.Track className="relative h-1.5 w-full grow overflow-hidden rounded-full bg-muted"> <SliderPrimitive.Range className="absolute h-full rounded-full bg-primary" /> </SliderPrimitive.Track> {/* Ticks and labels. Inset by half a thumb so they line up with the thumb's centre at every step. */} <span aria-hidden className="absolute inset-x-2.5 top-full mt-1.5"> {items.map((item, i) => { const percent = (i / last) * 100; const lit = i <= index; const current = i === index; return ( <span key={item.value} className="absolute top-0 flex -translate-x-1/2 flex-col items-center" style={{ left: `${percent}%` }}> <motion.span className={cn( "block h-1.5 w-0.5 origin-top rounded-full transition-colors duration-200", lit ? "bg-primary" : "bg-muted-foreground/35" )} initial={false} animate={{ scaleY: current && !reduceMotion ? 1.5 : 1 }} transition={reduceMotion ? { duration: 0 } : { duration: 0.2, ease: "easeOut" }} /> {!hideLabels && ( <span className={cn( "mt-2 cursor-pointer text-xs whitespace-nowrap transition-colors duration-200", current ? "font-medium text-foreground" : lit ? "text-foreground/70" : "text-muted-foreground", disabled && "cursor-default" )} > {item.label} </span> )} </span> ); })} </span> <SliderPrimitive.Thumb aria-label={ariaLabel} aria-valuetext={items[index]?.valueText} className={cn( "block size-5 rounded-full border-2 border-primary bg-background shadow-sm outline-none", "transition-[scale,box-shadow] duration-150 ease-out motion-reduce:transition-none", "group-data-[dragging]/slider:scale-110 focus-visible:ring-[3px] focus-visible:ring-ring/50", "data-[disabled]:pointer-events-none" )} /> </SliderPrimitive.Root> {name && <input type="hidden" name={name} value={items[index]?.value ?? ""} disabled={disabled} />} </div> ); }
| Prop | Type | Default | Description |
|---|---|---|---|
| steps | (string | { value: string; label: ReactNode; valueText?: string })[] | — | The choices, in order. Required. |
| value / defaultValue | string | — | The selected step's value. |
| onValueChange / onValueCommit | (value: string) => void | — | Called on change, and when the user finishes changing it. |
| name | string | — | Submits the selected value with a form. |
| hideLabels | boolean | false | Show only the tick marks. |
| aria-label | string | — | Accessible name for the slider. |
API Reference
Same as shadcn/ui: a single Slider that renders one thumb per value and forwards the Radix Slider props.
| Prop | Type | Default | Description |
|---|---|---|---|
| value / defaultValue | number[] | — | One value per thumb. |
| onValueChange / onValueCommit | (value: number[]) => void | — | Called while dragging / when the drag or key press ends. |
| min / max / step | number | 0 / 100 / 1 | Range and increment. |
| minStepsBetweenThumbs | number | 0 | Minimum gap between range thumbs, in steps. |
| orientation | "horizontal" | "vertical" | "horizontal" | Give vertical sliders a height. |
| aria-label / aria-labelledby | string | — | Forwarded to the thumbs (role="slider"). |
Accessibility
- Built on Radix Slider: each thumb is a
role="slider"witharia-valuemin,-maxand-now, operable with arrows, Page Up/Down and Home/End. - Label sliders with
aria-labeloraria-labelledby; the base and blocks move the label onto the thumbs, where screen readers look for it. - Value Slider and Stepped Slider set
aria-valuetextto the formatted value or step label, so “$240” or “50,000 requests” is read instead of a raw number. - Under prefers-reduced-motion thumbs resize instantly, the value bubble fades without leaning and ticks change without animating.