Overview
Dual thumbs for filter windows. Pointer capture tracks 1:1 while dragging, rubber-bands past ends, then springs back on release. Keyboard arrows nudge by step. Live values use tabular-nums.
Installation
Use the CLI to install the component automatically:
$ pnpm dlx shadcn@latest add https://ui.sanjid.in/r/range-slider.jsonInstall dependencies:
$ pnpm add motionAdd the utility function for class merging:
lib/utils.ts
tsx
1import { ClassValue, clsx } from "clsx";2import { twMerge } from "tailwind-merge";3 4export function cn(...inputs: ClassValue[]) {5 return twMerge(clsx(inputs));6}
Copy the component code into your project:
tsx
1"use client";2 3import React, { useCallback, useLayoutEffect, useRef, useState } from "react";4import { motion, useReducedMotion } from "motion/react";5import { cn } from "@/lib/utils";6 7export type RangeSliderProps = {8 min?: number;9 max?: number;10 step?: number;11 value?: [number, number];12 defaultValue?: [number, number];13 onValueChange?: (value: [number, number]) => void;14 className?: string;15 "aria-label"?: string;16};17 18const SPRING = { type: "spring" as const, bounce: 0, duration: 0.28 };19 20function clamp(n: number, lo: number, hi: number) {21 return Math.min(hi, Math.max(lo, n));22}23 24function snap(n: number, step: number, min: number) {25 return Math.round((n - min) / step) * step + min;26}27 28function normalizeRange(29 range: [number, number],30 min: number,31 max: number,32 step: number,33): [number, number] {34 const first = Number.isFinite(range?.[0]) ? range[0] : min;35 const second = Number.isFinite(range?.[1]) ? range[1] : max;36 return [37 clamp(snap(Math.min(first, second), step, min), min, max),38 clamp(snap(Math.max(first, second), step, min), min, max),39 ];40}41 42function DigitReadout({43 value,44 className,45}: {46 value: string;47 className?: string;48}) {49 const groupRef = useRef<HTMLSpanElement>(null);50 const [animating, setAnimating] = useState(true);51 const chars = value.split("");52 53 useLayoutEffect(() => {54 const el = groupRef.current;55 if (!el) return;56 setAnimating(false);57 void el.offsetHeight;58 setAnimating(true);59 }, [value]);60 61 return (62 <span63 ref={groupRef}64 className={cn("t-digit-group", animating && "is-animating", className)}65 >66 {chars.map((ch, i) => {67 const fromEnd = chars.length - 1 - i;68 const stagger = fromEnd === 1 ? "1" : fromEnd === 0 ? "2" : undefined;69 return (70 <span71 key={`${i}-${ch}`}72 className="t-digit"73 {...(stagger ? { "data-stagger": stagger } : {})}74 >75 {ch}76 </span>77 );78 })}79 </span>80 );81}82 83export function RangeSlider({84 min: minProp = 0,85 max: maxProp = 100,86 step: stepProp = 1,87 value: valueProp,88 defaultValue = [25, 75],89 onValueChange,90 className,91 "aria-label": ariaLabel = "Range",92}: RangeSliderProps) {93 const min = Number.isFinite(minProp) ? minProp : 0;94 const max = Number.isFinite(maxProp) && maxProp > min ? maxProp : min + 100;95 const step = Number.isFinite(stepProp) && stepProp > 0 ? stepProp : 1;96 const reduce = useReducedMotion();97 const trackRef = useRef<HTMLDivElement>(null);98 const isControlled = valueProp !== undefined;99 const [uncontrolled, setUncontrolled] = useState(defaultValue);100 const value = normalizeRange(101 isControlled ? valueProp : uncontrolled,102 min,103 max,104 step,105 );106 const [rubber, setRubber] = useState<[number, number] | null>(null);107 const active = useRef<"lo" | "hi" | null>(null);108 109 const display = rubber ?? value;110 111 const commit = useCallback(112 (next: [number, number]) => {113 const lo = clamp(snap(Math.min(next[0], next[1]), step, min), min, max);114 const hi = clamp(snap(Math.max(next[0], next[1]), step, min), min, max);115 const sorted: [number, number] = [lo, hi];116 if (!isControlled) setUncontrolled(sorted);117 onValueChange?.(sorted);118 },119 [isControlled, max, min, onValueChange, step],120 );121 122 const pct = (n: number) => ((n - min) / (max - min)) * 100;123 124 const valueFromClientX = (clientX: number) => {125 const el = trackRef.current;126 if (!el) return min;127 const rect = el.getBoundingClientRect();128 const raw = ((clientX - rect.left) / rect.width) * (max - min) + min;129 const overshoot = 0.08 * (max - min);130 return clamp(raw, min - overshoot, max + overshoot);131 };132 133 const onPointerDown = (which: "lo" | "hi", e: React.PointerEvent) => {134 e.preventDefault();135 active.current = which;136 (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);137 };138 139 const onPointerMove = (e: React.PointerEvent) => {140 if (!active.current) return;141 const v = valueFromClientX(e.clientX);142 const next: [number, number] =143 active.current === "lo" ? [v, value[1]] : [value[0], v];144 setRubber(next);145 };146 147 const onPointerUp = (e: React.PointerEvent) => {148 if (!active.current) return;149 try {150 (e.currentTarget as HTMLElement).releasePointerCapture(e.pointerId);151 } catch {152 /* Pointer cancellation can release capture before this handler runs. */153 }154 if (rubber) commit(rubber);155 setRubber(null);156 active.current = null;157 };158 159 const onPointerCancel = (e: React.PointerEvent) => {160 if (!active.current) return;161 try {162 (e.currentTarget as HTMLElement).releasePointerCapture(e.pointerId);163 } catch {164 /* The browser may already have released capture. */165 }166 setRubber(null);167 active.current = null;168 };169 170 const nudge = (which: "lo" | "hi", dir: -1 | 1) => {171 const next: [number, number] =172 which === "lo"173 ? [clamp(value[0] + dir * step, min, value[1]), value[1]]174 : [value[0], clamp(value[1] + dir * step, value[0], max)];175 commit(next);176 };177 178 const loPct = pct(clamp(display[0], min, max));179 const hiPct = pct(clamp(display[1], min, max));180 const fillLeft = Math.min(loPct, hiPct);181 const fillWidth = Math.abs(hiPct - loPct);182 183 const loLabel = String(Math.round(clamp(display[0], min, max)));184 const hiLabel = String(Math.round(clamp(display[1], min, max)));185 186 return (187 <div className={cn("w-full select-none", className)}>188 <div className="mb-2 flex justify-between text-xs text-[var(--color-ink-muted)] tabular-nums">189 <DigitReadout value={loLabel} />190 <DigitReadout value={hiLabel} />191 </div>192 <div193 ref={trackRef}194 className="relative h-10 touch-none"195 aria-label={ariaLabel}196 >197 <div className="absolute top-1/2 right-0 left-0 h-1.5 -translate-y-1/2 rounded-full bg-[var(--color-paper-2)]" />198 <motion.div199 className="absolute top-1/2 h-1.5 -translate-y-1/2 rounded-full bg-[var(--color-ink)]"200 animate={{ left: `${fillLeft}%`, width: `${fillWidth}%` }}201 transition={reduce ? { duration: 0.1 } : SPRING}202 initial={false}203 />204 {(["lo", "hi"] as const).map((which) => {205 const v = which === "lo" ? display[0] : display[1];206 const p = pct(clamp(v, min, max));207 return (208 <motion.button209 key={which}210 type="button"211 aria-label={which === "lo" ? "Minimum" : "Maximum"}212 aria-valuemin={min}213 aria-valuemax={max}214 aria-valuenow={Math.round(clamp(v, min, max))}215 role="slider"216 tabIndex={0}217 onPointerDown={(e) => onPointerDown(which, e)}218 onPointerMove={onPointerMove}219 onPointerUp={onPointerUp}220 onPointerCancel={onPointerCancel}221 onKeyDown={(e) => {222 if (e.key === "ArrowLeft" || e.key === "ArrowDown") {223 e.preventDefault();224 nudge(which, -1);225 } else if (e.key === "ArrowRight" || e.key === "ArrowUp") {226 e.preventDefault();227 nudge(which, 1);228 } else if (e.key === "PageDown" || e.key === "PageUp") {229 e.preventDefault();230 const direction = e.key === "PageDown" ? -1 : 1;231 const amount = step * 10 * direction;232 commit(233 which === "lo"234 ? [value[0] + amount, value[1]]235 : [value[0], value[1] + amount],236 );237 } else if (e.key === "Home" || e.key === "End") {238 e.preventDefault();239 const edge = e.key === "Home" ? min : max;240 commit(which === "lo" ? [edge, value[1]] : [value[0], edge]);241 }242 }}243 whileTap={reduce ? undefined : { scale: 0.96 }}244 className={cn(245 "absolute top-1/2 size-10 -translate-x-1/2 -translate-y-1/2 outline-none",246 "flex items-center justify-center",247 "rounded-full focus-visible:ring-2 focus-visible:ring-[var(--color-focus)]",248 )}249 style={{ left: `${p}%` }}250 animate={{ left: `${p}%` }}251 transition={252 rubber ? { duration: 0 } : reduce ? { duration: 0.1 } : SPRING253 }254 initial={false}255 >256 <span className="size-5 rounded-full bg-[var(--color-paper)] shadow-[0_1px_4px_rgba(0,0,0,0.2)] ring-1 ring-[var(--color-rule)]" />257 </motion.button>258 );259 })}260 </div>261 </div>262 );263}
Adjust import paths according to your folder structure.
Basic Usage
tsx
1import { RangeSlider } from "@/components/ui/range-slider";2 3<RangeSlider4 min={0}5 max={120}6 step={2}7 value={range}8 onValueChange={setRange}9/>
Props
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| min | number | No | 0 | Range minimum. |
| max | number | No | 100 | Range maximum. |
| step | number | No | 1 | Snap increment. |
| value | [number, number] | No | — | Controlled low/high pair. |
| onValueChange | (value: [number, number]) => void | No | — | Fires on commit (and keyboard). |
Best Practices
- Keep thumb hit areas ≥40px even if the visual knob is smaller.
- Prefer even
stepvalues for SLA / price windows. - Commit on pointer-up so mid-drag doesn’t thrash filters.