View as Markdown

Shadcn Range Slider

A slider for a single value or a range with two or more thumbs. It supports steps, a minimum distance between thumbs, formatted values, marks, tooltips that merge when the thumbs get close, vertical layout and native form submission. Each thumb is a real range input, so it works with the keyboard and screen readers out of the box.

40

Installation

npx shadcn@latest add @shadcnuikit/range-slider1

This adds components/ui/range-slider.tsx, the field component it depends on, and a demo file. Set up the registry once as described in Shadcn CLI. Range Slider is free and installs without an API key.

Manual installation

Install the dependencies and the field component:

npm install @ui-sdk/react@beta
npx shadcn@latest add field

Copy the source into components/ui/range-slider.tsx:

components/ui/range-slider.tsx
"use client";
import * as React from "react";import { Field as FieldPrimitive, FieldDescription as FieldDescriptionPrimitive, FieldLabel as FieldLabelPrimitive,} from "@ui-sdk/react/field";import { Slider as SliderPrimitive, SliderControl as SliderControlPrimitive, SliderIndicator as SliderIndicatorPrimitive, SliderThumb as SliderThumbPrimitive, SliderTrack as SliderTrackPrimitive, SliderValue as SliderValuePrimitive, createSliderController,} from "@ui-sdk/react/slider";
import { cn } from "@/lib/utils";import { Field, FieldDescription, FieldLabel } from "@/components/ui/field";
type WithClassName<T> = Omit<T, "className"> & { className?: string };
type RangeSliderProps<Value extends number | number[]> = WithClassName< Parameters<typeof SliderPrimitive<Value>>[0]>;
function RangeSlider<Value extends number | number[] = number | number[]>({ className, ...props}: RangeSliderProps<Value>) { return ( <SliderPrimitive<Value> className={cn( "group/range-slider flex w-full flex-col gap-3 data-disabled:opacity-50", "data-[orientation=vertical]:h-full data-[orientation=vertical]:w-auto data-[orientation=vertical]:items-center", className, )} {...props} /> );}
function RangeSliderControl({ className, ...props}: WithClassName<React.ComponentProps<typeof SliderControlPrimitive>>) { return ( <SliderControlPrimitive className={cn( "relative flex w-full cursor-pointer touch-none items-center py-2 select-none data-disabled:cursor-not-allowed", "data-[orientation=vertical]:min-h-40 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-1 data-[orientation=vertical]:flex-col data-[orientation=vertical]:px-2 data-[orientation=vertical]:py-0", className, )} {...props} /> );}
function RangeSliderTrack({ className, ...props}: WithClassName<React.ComponentProps<typeof SliderTrackPrimitive>>) { return ( <SliderTrackPrimitive className={cn( "bg-muted relative grow rounded-full", "data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:w-1.5", className, )} {...props} /> );}
type RangeSliderIndicatorProps = WithClassName< React.ComponentProps<typeof SliderIndicatorPrimitive>> & { /** Shows one tooltip for both thumbs of a range once their own tooltips would overlap. */ tooltip?: (values: number[]) => React.ReactNode; tooltipVisibility?: "active" | "always";};
function RangeSliderIndicator({ className, tooltip, tooltipVisibility = "active", children, ...props}: RangeSliderIndicatorProps) { return ( <SliderIndicatorPrimitive className={cn("bg-primary rounded-full", className)} {...props} > {tooltip ? (state) => Array.isArray(state.value) && state.value.length === 2 ? ( <RangeSliderMergedTooltip orientation={state.orientation} visibility={tooltipVisibility} > {tooltip(state.value)} </RangeSliderMergedTooltip> ) : null : children} </SliderIndicatorPrimitive> );}
function RangeSliderMergedTooltip({ orientation, visibility, children,}: { orientation: "horizontal" | "vertical"; visibility: "active" | "always"; children: React.ReactNode;}) { const ref = React.useRef<HTMLSpanElement>(null); const [merged, setMerged] = React.useState(false);
const measure = React.useCallback(() => { const indicator = ref.current?.parentElement; const tooltips = indicator?.parentElement?.querySelectorAll<HTMLElement>( "[data-slot=range-slider-tooltip]", ); if (!indicator || !tooltips || tooltips.length < 2) return; const vertical = orientation === "vertical"; const sizeOf = (el: HTMLElement) => vertical ? el.offsetHeight : el.offsetWidth; const distance = sizeOf(indicator); const needed = (sizeOf(tooltips[0]) + sizeOf(tooltips[1])) / 2 + 4; setMerged(distance < needed); }, [orientation]);
React.useLayoutEffect(measure);
React.useEffect(() => { const indicator = ref.current?.parentElement; if (!indicator) return; const observer = new ResizeObserver(measure); observer.observe(indicator); return () => observer.disconnect(); }, [measure]);
return ( <span ref={ref} aria-hidden="true" data-slot="range-slider-merged-tooltip" data-merged={merged || undefined} className={cn( "bg-primary text-primary-foreground pointer-events-none absolute rounded-md px-2 py-1 text-xs font-medium whitespace-nowrap tabular-nums opacity-0 shadow-sm transition-opacity", orientation === "horizontal" ? "bottom-full left-1/2 mb-3.5 -translate-x-1/2" : "start-full top-1/2 ms-4 -translate-y-1/2", merged && (visibility === "always" ? "opacity-100" : "group-hover/range-slider:opacity-100 group-has-focus-visible/range-slider:opacity-100 group-data-dragging/range-slider:opacity-100"), )} > {children} </span> );}
type RangeSliderThumbProps = WithClassName< React.ComponentProps<typeof SliderThumbPrimitive>> & { tooltip?: (value: number) => React.ReactNode; tooltipVisibility?: "active" | "always";};
function RangeSliderThumb({ className, tooltip, tooltipVisibility = "active", children, ...props}: RangeSliderThumbProps) { return ( <SliderThumbPrimitive className={cn( "group/thumb border-primary bg-background block size-4 shrink-0 cursor-grab rounded-full border-2 shadow-sm transition-[box-shadow] outline-none", "hover:ring-ring/30 has-focus-visible:ring-ring/50 data-dragging:ring-ring/50 hover:ring-4 has-focus-visible:ring-4 data-dragging:cursor-grabbing data-dragging:ring-4", "data-disabled:cursor-not-allowed data-disabled:hover:ring-0", className, )} {...props} > {tooltip ? (state) => ( <span aria-hidden="true" data-slot="range-slider-tooltip" className={cn( "bg-primary text-primary-foreground pointer-events-none absolute rounded-md px-2 py-1 text-xs font-medium whitespace-nowrap tabular-nums shadow-sm transition-opacity", "group-data-[orientation=horizontal]/thumb:bottom-full group-data-[orientation=horizontal]/thumb:left-1/2 group-data-[orientation=horizontal]/thumb:mb-2.5 group-data-[orientation=horizontal]/thumb:-translate-x-1/2", "group-data-[orientation=vertical]/thumb:start-full group-data-[orientation=vertical]/thumb:top-1/2 group-data-[orientation=vertical]/thumb:ms-3 group-data-[orientation=vertical]/thumb:-translate-y-1/2", tooltipVisibility === "active" && "opacity-0 group-hover/thumb:opacity-100 group-has-focus-visible/thumb:opacity-100 group-data-dragging/thumb:opacity-100", "group-has-data-merged/range-slider:opacity-0!", )} > {tooltip(state.thumbValue)} </span> ) : children} </SliderThumbPrimitive> );}
function RangeSliderValue({ className, ...props}: WithClassName<React.ComponentProps<typeof SliderValuePrimitive>>) { return ( <SliderValuePrimitive className={cn("text-muted-foreground text-sm tabular-nums", className)} {...props} /> );}
type RangeSliderMark = number | { value: number; label?: React.ReactNode };
type RangeSliderMarksProps = Omit<React.ComponentProps<"div">, "children"> & { marks: RangeSliderMark[]; min?: number; max?: number;};
function RangeSliderMarks({ marks, min = 0, max = 100, className, ...props}: RangeSliderMarksProps) { return ( <div aria-hidden="true" data-slot="range-slider-marks" className={cn( "text-muted-foreground relative -mt-2 h-6 w-full text-xs", className, )} {...props} > {marks.map((mark) => { const { value, label } = typeof mark === "number" ? { value: mark, label: mark } : mark; return ( <span key={value} style={ { "--mark-position": `${((value - min) / (max - min)) * 100}%`, } as React.CSSProperties } className="absolute start-(--mark-position) top-0 flex -translate-x-1/2 flex-col items-center gap-1 rtl:translate-x-1/2" > <span className="bg-muted-foreground/40 h-1.5 w-px" /> {label != null && <span className="whitespace-nowrap tabular-nums">{label}</span>} </span> ); })} </div> );}
function RangeSliderField({ className, ...props}: WithClassName<React.ComponentProps<typeof FieldPrimitive>>) { return <FieldPrimitive render={<Field className={className} />} {...props} />;}
function RangeSliderLabel({ className, ...props}: WithClassName<React.ComponentProps<typeof FieldLabelPrimitive>>) { return ( <FieldLabelPrimitive render={<FieldLabel className={className} />} {...props} /> );}
function RangeSliderDescription({ className, ...props}: WithClassName<React.ComponentProps<typeof FieldDescriptionPrimitive>>) { return ( <FieldDescriptionPrimitive render={<FieldDescription className={className} />} {...props} /> );}
export { RangeSlider, RangeSliderControl, RangeSliderTrack, RangeSliderIndicator, RangeSliderThumb, RangeSliderValue, RangeSliderMarks, RangeSliderField, RangeSliderLabel, RangeSliderDescription, createSliderController,};export type { RangeSliderProps, RangeSliderIndicatorProps, RangeSliderThumbProps, RangeSliderMark,};

Usage

import {
  RangeSlider,
  RangeSliderControl,
  RangeSliderIndicator,
  RangeSliderThumb,
  RangeSliderTrack,
} from "@/components/ui/range-slider";
<RangeSlider defaultValue={[25, 75]}>
  <RangeSliderControl>
    <RangeSliderTrack>
      <RangeSliderIndicator />
      <RangeSliderThumb index={0} aria-label="Minimum" />
      <RangeSliderThumb index={1} aria-label="Maximum" />
    </RangeSliderTrack>
  </RangeSliderControl>
</RangeSlider>

The value is a number for one thumb, or an array with one number per thumb. Render one RangeSliderThumb per value and give each its index, from 0.

With a label

<RangeSliderField>
  <RangeSlider defaultValue={40}>
    <div className="flex items-center justify-between">
      <RangeSliderLabel>Volume</RangeSliderLabel>
      <RangeSliderValue />
    </div>
    <RangeSliderControl>
      <RangeSliderTrack>
        <RangeSliderIndicator />
        <RangeSliderThumb />
      </RangeSliderTrack>
    </RangeSliderControl>
  </RangeSlider>
  <RangeSliderDescription>Applies to every device.</RangeSliderDescription>
</RangeSliderField>

RangeSliderField ties RangeSliderLabel and RangeSliderDescription to the thumb. RangeSliderValue shows the formatted value, and a range joined with an en dash.

Controlled

const [value, setValue] = React.useState([20, 80]);

<RangeSlider value={value} onValueChange={setValue}>...</RangeSlider>;

onValueChange runs on every step of a drag or key. Use onValueCommit to save once the pointer lifts or the key comes up.

In a form

<RangeSlider name="price" defaultValue={[20, 80]}>...</RangeSlider>

With a name, a single value submits as a number and a range as "start/end", like "20/80".

Examples

Range

Two thumbs select a range. The indicator fills the track between them.

25 – 75

Step

step sets how far one move goes, counted from min.

50

Minimum Distance

minStepsBetweenThumbs keeps neighbouring thumbs that many steps apart. Thumbs never pass each other.

30 – 60

The thumbs stay at least 20 apart.

Format

format takes Intl.NumberFormat options or a function. It changes RangeSliderValue and what screen readers announce.

$200 – $800

Marks

RangeSliderMarks draws ticks and labels under the track. Pass the same min and max as the slider when they are not 0 and 100.

Tooltip

Pass a tooltip function to RangeSliderThumb. It shows while the thumb is hovered, focused or dragged.

Merged Tooltip

Give RangeSliderIndicator a tooltip too. When the two thumb tooltips would overlap, they hide and one tooltip like "40 - 43" shows over the indicator instead. Drag the thumbs apart to see them split. tooltipVisibility="always" keeps the tooltips visible.

Vertical

orientation="vertical" stands the slider up. It grows upward and takes the height of its parent, with a minimum of 10rem.

Disabled

20 – 70

More layouts built with Range Slider, such as price inputs, histograms and equalizers, are on the Range Slider components page.

API Reference

RangeSlider

The root.

PropTypeDefaultDescription
valuenumber, number[]The value: a number for one thumb, or one number per thumb. Pass it to control the slider.
defaultValuenumber, number[]minThe value at first, when uncontrolled. A form reset returns to it.
onValueChange(value, details) => voidRuns on every step of a drag or key. details.thumb says which thumb moved, details.cancel() stops it.
onValueCommit(value, details) => voidRuns once an interaction ends: the pointer lifts, the key comes up, or a screen reader adjusts it.
minnumber0The lowest value.
maxnumber100The highest value. When the steps from min don't land on it, the highest step below it is the end.
stepnumber1How far one step moves, from min.
largeStepnumber10 stepsHow far PageUp, PageDown and Shift with an arrow key move.
minStepsBetweenThumbsnumber0How many steps apart neighbouring thumbs stay.
orientation"horizontal", "vertical""horizontal"The axis. Vertical sliders grow upward.
disabledbooleanfalseThumbs can't be focused or moved, and nothing is submitted.
readOnlybooleanfalseStays focusable and submitted, but drags, keys and screen readers can't change it.
requiredbooleanfalseAdds data-required. A slider always has a value, so it never blocks a form.
namestringThe name it submits under: the number, or a range as "start/end".
formstringThe id of a form to belong to, when the slider is outside it.
formatIntl.NumberFormatOptions, (value) => stringHow values read for screen readers and RangeSliderValue.
localestringpage langThe locale values are formatted in.
controllerSliderControllerMoves the slider from anywhere. Create one with createSliderController().
classNamestringClasses for the root.

The root and its parts have data-orientation, data-disabled, data-readonly, data-required and data-dragging attributes for styling.

RangeSliderControl, RangeSliderTrack

RangeSliderControl is where presses land: a press moves the nearest thumb there. RangeSliderTrack is the rail the thumbs move along. Both take className.

RangeSliderIndicator

The filled part of the track: up to a single thumb, or between the first and last thumb of a range.

PropTypeDefaultDescription
tooltip(values: number[]) => ReactNodeFor a two thumb range. Shows one tooltip over the indicator once the thumb tooltips would overlap, and hides the thumb tooltips meanwhile.
tooltipVisibility"active", "always""active"active shows the merged tooltip while the slider is hovered, focused or dragged. always keeps it visible.
classNamestringClasses for the indicator.

The merged tooltip measures the thumb tooltips, so both thumbs need a tooltip for it to appear. Use the same tooltipVisibility on the indicator and the thumbs. The merged tooltip has data-slot="range-slider-merged-tooltip" and data-merged while it is shown.

RangeSliderThumb

A thumb, with the native range input inside it that takes focus.

PropTypeDefaultDescription
indexnumber0Which value the thumb shows, from 0. Give each thumb of a range its own.
tooltip(value: number) => ReactNodeShows the thumb value in a tooltip above it, or beside it when vertical.
tooltipVisibility"active", "always""active"active shows the tooltip while the thumb is hovered, focused or dragged. always keeps it visible.
aria-labelstringNames the thumb. Goes to the range input, like aria-labelledby and aria-describedby.
classNamestringClasses for the thumb.

The thumb has data-index and data-dragging attributes. The tooltip has data-slot="range-slider-tooltip".

RangeSliderValue

An output with the formatted value. A range is joined with an en dash. Children replace the text.

RangeSliderMarks

PropTypeDefaultDescription
marks(number, { value, label? })[]Where to draw ticks. A number is its own label. An object can set any label, or none.
minnumber0Match the slider min.
maxnumber100Match the slider max.
classNamestringClasses for the marks row.

Marks are hidden from screen readers and are laid out for horizontal sliders.

RangeSliderField, RangeSliderLabel, RangeSliderDescription

The ui-sdk field parts rendered as the shadcn/ui Field, FieldLabel and FieldDescription. Wrap the slider in RangeSliderField and the label and description point at the first thumb.

createSliderController

const [controller] = React.useState(() => createSliderController<number[]>());

<RangeSlider controller={controller} defaultValue={[20, 80]}>...</RangeSlider>;

controller.getValue();
controller.setValue([30, 60]); // clamped, snapped to the step and sorted
controller.focus(1); // the second thumb

Keyboard

KeyAction
TabMoves focus to the next thumb.
ArrowRight, ArrowUpIncreases the focused thumb by step.
ArrowLeft, ArrowDownDecreases the focused thumb by step.
Shift + arrow keyMoves by largeStep.
PageUp, PageDownIncreases or decreases by largeStep.
HomeMoves the focused thumb as low as it can go: min, or up to the thumb before it.
EndMoves the focused thumb as high as it can go: max, or up to the thumb after it.

Every arrow works whatever the orientation. In right to left layouts, ArrowLeft and ArrowRight swap on a horizontal slider.

Accessibility

  • Every thumb is a native range input with the slider role, so screen readers on phones can adjust it with their own gestures.
  • Name each thumb with aria-label, or wrap a single thumb slider in RangeSliderField with a RangeSliderLabel. For a range, label each thumb, like "Minimum price" and "Maximum price".
  • Values are announced from format, so a currency reads as "$200" instead of "200".
  • Tooltips and marks are hidden from screen readers, since each thumb already says its value.
  • A disabled slider can't be focused and is not submitted. A read-only one stays focusable and announces that it is read-only.

For AI Agents

When to use

  • Picking a number on a continuous scale: volume, opacity, zoom, a percentage.
  • Picking a range: price filters, age ranges, time windows, with two thumbs.
  • Settings where a rough value is fine and dragging is faster than typing.

When not to use

  • Exact numbers that people type, such as a quantity or an amount. Use a Number Input.
  • A few named options, such as Small, Medium and Large. Use a Radio Group or a Toggle group.
  • Before and after image sliders. Use Comparison.

Agent notes

  • Import from @/components/ui/range-slider. The exports are RangeSlider, RangeSliderControl, RangeSliderTrack, RangeSliderIndicator, RangeSliderThumb, RangeSliderValue, RangeSliderMarks, RangeSliderField, RangeSliderLabel, RangeSliderDescription and createSliderController.
  • Keep the structure: RangeSlider > RangeSliderControl > RangeSliderTrack > RangeSliderIndicator and one RangeSliderThumb per value.
  • onValueChange receives the same shape you pass: a number for one thumb, an array for a range. Unlike the shadcn/ui Slider, a single value is not wrapped in an array.
  • tooltip props are functions, so a file that passes them needs "use client".
  • The merged indicator tooltip only appears when both thumbs also have a tooltip.
  • Pass min and max to RangeSliderMarks whenever the slider does not run from 0 to 100.
  • Give a vertical slider a height through its parent or className, like h-48.

Resources