Menu

Components

Slider

A track and a thumb to choose a number by feel, or two thumbs to choose a range.

Introduction

A slider is for a number that has no exact answer and is tuned by feel: a volume, a price range, a zoom, a brightness. Where a person needs to type an exact number, use a Number Field, and it can sit beside a slider.

  • One thumb for a number, and a list of numbers for a range, with a thumb for each. A press on the track moves the nearest thumb, and thumbs cannot cross.
  • The value is written for people with formatOptions: as a percent, a price, a unit.
  • Marks on the track, a bubble with the number over a thumb, a fill that starts in the middle, five colors, three sizes, and a vertical form.
  • Built on react-aria's Slider: the thumbs are range inputs, so a form gets the number, the keyboard works, and a screen reader hears the label and the value.

Installation

centerUI has no CLI or registry yet: components are copied into your project.

# bun
bun add react-aria-components tailwind-variants tailwind-merge clsx

# pnpm
pnpm add react-aria-components tailwind-variants tailwind-merge clsx

# npm
npm install react-aria-components tailwind-variants tailwind-merge clsx

Manual installation

Copy these files into your project and keep the paths, or adjust the imports.

1. Add the styles

src/types/slider-styles.tsShow code
import { tv } from "tailwind-variants";

// Styles for Slider. The color of the fill and the thumb is the `--slider-color`
// variable, set by the `color` variant, so a color is written in one place. The
// place of a thumb (its left, or its bottom) is set by react-aria as an inline
// style, and the fill and the marks are placed by the component the same way.
export const sliderStyles = tv({
  slots: {
    root: "group/slider flex flex-col gap-2 text-fg",
    header: "flex items-center justify-between gap-3 text-sm",
    label: "font-medium",
    output: "font-mono text-xs text-muted-fg tabular-nums",
    description: "m-0 text-sm text-muted-fg",
    // The part that takes the press: taller than the bar, so it is easy to hit.
    track:
      "relative flex touch-none items-center data-disabled:cursor-not-allowed data-disabled:opacity-50",
    bar: "absolute overflow-hidden rounded-full bg-fg/15",
    fill: "absolute rounded-full bg-(--slider-color)",
    tick: "absolute size-1 rounded-full bg-bg/70",
    markLabel: "absolute text-xs whitespace-nowrap text-muted-fg tabular-nums",
    thumb: [
      "group/thumb rounded-full border-2 border-(--slider-color) bg-bg shadow-sm outline-none",
      "transition-[transform,box-shadow] duration-150 motion-reduce:transition-none",
      "data-hovered:shadow-md data-dragging:scale-110",
      "data-focus-visible:ring-2 data-focus-visible:ring-ring data-focus-visible:ring-offset-2 data-focus-visible:ring-offset-bg",
    ],
    tooltip: [
      "pointer-events-none absolute rounded-md bg-fg px-1.5 py-0.5 font-mono text-xs whitespace-nowrap text-bg tabular-nums",
      "opacity-0 transition-opacity duration-150 motion-reduce:transition-none",
      "group-data-dragging/thumb:opacity-100 group-data-focus-visible/thumb:opacity-100 group-data-hovered/thumb:opacity-100",
    ],
  },
  variants: {
    orientation: {
      horizontal: {
        root: "w-full",
        track: "w-full",
        bar: "inset-x-0 top-1/2 -translate-y-1/2",
        fill: "inset-y-0",
        thumb: "top-1/2",
        tooltip: "bottom-full left-1/2 mb-2.5 -translate-x-1/2",
      },
      vertical: {
        root: "h-full w-fit items-center",
        track: "h-48 justify-center",
        bar: "inset-y-0 left-1/2 -translate-x-1/2",
        fill: "inset-x-0",
        thumb: "left-1/2",
        tooltip: "top-1/2 right-full mr-2.5 -translate-y-1/2",
      },
    },
    size: { sm: {}, md: {}, lg: {} },
    color: {
      primary: { root: "[--slider-color:var(--primary)]" },
      secondary: { root: "[--slider-color:var(--secondary)]" },
      success: { root: "[--slider-color:var(--success)]" },
      warning: { root: "[--slider-color:var(--warning)]" },
      danger: { root: "[--slider-color:var(--danger)]" },
    },
  },
  compoundVariants: [
    {
      orientation: "horizontal",
      size: "sm",
      class: { track: "h-4", bar: "h-1" },
    },
    {
      orientation: "horizontal",
      size: "md",
      class: { track: "h-5", bar: "h-1.5" },
    },
    {
      orientation: "horizontal",
      size: "lg",
      class: { track: "h-6", bar: "h-2.5" },
    },
    {
      orientation: "vertical",
      size: "sm",
      class: { track: "w-4", bar: "w-1" },
    },
    {
      orientation: "vertical",
      size: "md",
      class: { track: "w-5", bar: "w-1.5" },
    },
    {
      orientation: "vertical",
      size: "lg",
      class: { track: "w-6", bar: "w-2.5" },
    },
    { size: "sm", class: { thumb: "size-4" } },
    { size: "md", class: { thumb: "size-5" } },
    { size: "lg", class: { thumb: "size-6" } },
  ],
  defaultVariants: { orientation: "horizontal", size: "md", color: "primary" },
});

2. Add the Slider file

src/components/ui/slider/slider.tsxShow code
"use client";

import { type ReactNode, useId } from "react";
import {
  Slider as AriaSlider,
  Label,
  SliderOutput,
  SliderThumb,
  SliderTrack,
} from "react-aria-components";
import { cn } from "@/lib/cn";
import { sliderStyles } from "@/types/slider-styles";

/** A number on the track that is marked, and if you like named. */
export interface SliderMark {
  value: number;
  /** What it says under (or beside) the mark, such as `"50%"`. */
  label?: ReactNode;
}

export interface SliderProps<T extends number | number[] = number> {
  /** The value, for a controlled slider: a number, or two or more numbers for a range with a thumb for each. */
  value?: T;
  /** The value to start with, for an uncontrolled slider. Defaults to the smallest value. */
  defaultValue?: T;
  /** Called as a thumb moves, with the value in the shape it was given. */
  onChange?: (value: T) => void;
  /** Called when a thumb is let go, or a key press is done. Use it to save, and `onChange` to show. */
  onChangeEnd?: (value: T) => void;
  /** The smallest value. Defaults to `0`. */
  minValue?: number;
  /** The biggest value. Defaults to `100`. */
  maxValue?: number;
  /** How far one move goes: the arrow keys and the places a thumb can stop. Defaults to `1`. */
  step?: number;
  /** A label above the track, at the left. Without one, name the slider with `aria-label`. */
  label?: ReactNode;
  /** A line under the track that says more. */
  description?: ReactNode;
  /** The number, above the track at the right: `40`, or `20 – 80` for a range. Defaults to `false`. */
  showValue?: boolean;
  /** How the numbers are written, as for `Intl.NumberFormat`: `{ style: "percent" }` or `{ style: "currency", currency: "USD" }`. */
  formatOptions?: Intl.NumberFormatOptions;
  /** Lie along the width, or stand up. Defaults to `horizontal`. */
  orientation?: "horizontal" | "vertical";
  /** How thick the track and the thumb are. Defaults to `md`. */
  size?: "sm" | "md" | "lg";
  /** The color of the fill and the thumb. Defaults to `primary`. */
  color?: "primary" | "secondary" | "success" | "warning" | "danger";
  /**
   * Marks on the track, at each number in the list or each with a label. `true`
   * puts one at every step. A press on a mark goes to it.
   */
  marks?: boolean | (number | SliderMark)[];
  /** A small bubble with the number over a thumb while it is pointed at, held or focused. Defaults to `false`. */
  showTooltip?: boolean;
  /** Where the fill starts, for a slider with one thumb: `0` on a slider from -50 to 50 fills from the middle. Defaults to the smallest value. */
  origin?: number;
  /** Fill the track up to the thumb, or between the thumbs. Defaults to `true`. */
  showFill?: boolean;
  /** Names each thumb for a screen reader on a range. Defaults to "Minimum" and "Maximum" for two thumbs. */
  thumbLabels?: string[];
  /** The name of the form field that holds the number. A range sends one for each thumb, under the same name. */
  name?: string;
  isDisabled?: boolean;
  "aria-label"?: string;
  className?: string;
}

const MAX_MARKS = 101;

// The list of marks to draw, from what was asked for.
function toMarks(
  marks: SliderProps["marks"],
  min: number,
  max: number,
  step: number,
): SliderMark[] {
  if (!marks) return [];
  if (marks === true) {
    const list: SliderMark[] = [];
    const count = Math.min(Math.floor((max - min) / step), MAX_MARKS - 1);
    for (let i = 0; i <= count; i++) list.push({ value: min + i * step });
    return list;
  }
  return marks
    .map((mark) => (typeof mark === "number" ? { value: mark } : mark))
    .filter((mark) => mark.value >= min && mark.value <= max);
}

/**
 * A slider: a track and a thumb that is moved along it to choose a number, or
 * two thumbs to choose a range. Use it for a number that has no exact answer and
 * is tuned by feel: a volume, a price range, a zoom, a brightness.
 *
 * Built on react-aria's Slider, so it works with a mouse, a finger and the
 * keyboard (the arrow keys move a thumb by one step, Page Up and Page Down by
 * more, Home and End to the ends), the thumbs are real range inputs for a form,
 * and a screen reader hears the label and the value.
 *
 * Give it a number for one thumb, or a list of numbers for a range. A press on
 * the track moves the nearest thumb there, and thumbs cannot cross.
 *
 * @example
 * <Slider label="Volume" showValue defaultValue={40} onChange={setVolume} />
 * <Slider label="Price" showValue defaultValue={[20, 80]} formatOptions={{ style: "currency", currency: "USD", maximumFractionDigits: 0 }} />
 */
export function Slider<T extends number | number[] = number>({
  value,
  defaultValue,
  onChange,
  onChangeEnd,
  minValue = 0,
  maxValue = 100,
  step = 1,
  label,
  description,
  showValue = false,
  formatOptions,
  orientation = "horizontal",
  size = "md",
  color = "primary",
  marks,
  showTooltip = false,
  origin,
  showFill = true,
  thumbLabels,
  name,
  isDisabled,
  "aria-label": ariaLabel,
  className,
}: SliderProps<T>) {
  const styles = sliderStyles({ orientation, size, color });
  const isVertical = orientation === "vertical";
  const descriptionId = useId();
  const markList = toMarks(marks, minValue, maxValue, step);
  const hasMarkLabels = markList.some((mark) => mark.label !== undefined);
  const hasHeader = Boolean(label) || showValue;
  const span = maxValue - minValue || 1;
  const percentOf = (n: number) => ((n - minValue) / span) * 100;

  return (
    <AriaSlider<T>
      value={value}
      defaultValue={defaultValue}
      onChange={onChange}
      onChangeEnd={onChangeEnd}
      minValue={minValue}
      maxValue={maxValue}
      step={step}
      orientation={orientation}
      formatOptions={formatOptions}
      isDisabled={isDisabled}
      aria-label={label ? undefined : (ariaLabel ?? "Slider")}
      aria-describedby={description ? descriptionId : undefined}
      // Room for what the labels of the marks say, which hangs off the track.
      className={cn(
        styles.root(),
        hasMarkLabels && (isVertical ? "mr-10" : "mb-6"),
        className,
      )}
    >
      {hasHeader ? (
        <div className={styles.header()}>
          {label ? <Label className={styles.label()}>{label}</Label> : <span />}
          {showValue ? <SliderOutput className={styles.output()} /> : null}
        </div>
      ) : null}

      <SliderTrack className={styles.track()}>
        {({ state }) => {
          const count = state.values.length;
          const thumbAt = (i: number) => state.getThumbPercent(i) * 100;
          let start: number;
          let end: number;
          if (count === 1) {
            const from = percentOf(origin ?? minValue);
            [start, end] = [
              Math.min(from, thumbAt(0)),
              Math.max(from, thumbAt(0)),
            ];
          } else {
            [start, end] = [thumbAt(0), thumbAt(count - 1)];
          }

          return (
            <>
              <div className={styles.bar()}>
                {showFill ? (
                  <div
                    className={styles.fill()}
                    style={
                      isVertical
                        ? { bottom: `${start}%`, height: `${end - start}%` }
                        : { left: `${start}%`, width: `${end - start}%` }
                    }
                  />
                ) : null}
              </div>

              {markList.map((mark) => (
                <span key={mark.value} aria-hidden="true">
                  <span
                    className={styles.tick()}
                    style={
                      isVertical
                        ? {
                            bottom: `${percentOf(mark.value)}%`,
                            left: "50%",
                            transform: "translate(-50%, 50%)",
                          }
                        : {
                            left: `${percentOf(mark.value)}%`,
                            top: "50%",
                            transform: "translate(-50%, -50%)",
                          }
                    }
                  />
                  {mark.label !== undefined ? (
                    <span
                      className={styles.markLabel()}
                      style={
                        isVertical
                          ? {
                              bottom: `${percentOf(mark.value)}%`,
                              left: "100%",
                              marginLeft: 10,
                              transform: "translateY(50%)",
                            }
                          : {
                              left: `${percentOf(mark.value)}%`,
                              top: "100%",
                              marginTop: 6,
                              transform: "translateX(-50%)",
                            }
                      }
                    >
                      {mark.label}
                    </span>
                  ) : null}
                </span>
              ))}

              {state.values.map((_, i) => (
                <SliderThumb
                  // biome-ignore lint/suspicious/noArrayIndexKey: a thumb is its position
                  key={i}
                  index={i}
                  name={name}
                  aria-label={
                    thumbLabels?.[i] ??
                    (count === 2 ? ["Minimum", "Maximum"][i] : undefined)
                  }
                  className={styles.thumb()}
                >
                  {showTooltip ? (
                    <span aria-hidden="true" className={styles.tooltip()}>
                      {state.getThumbValueLabel(i)}
                    </span>
                  ) : null}
                </SliderThumb>
              ))}
            </>
          );
        }}
      </SliderTrack>

      {description ? (
        <p id={descriptionId} className={styles.description()}>
          {description}
        </p>
      ) : null}
    </AriaSlider>
  );
}

3. Use it

import { Slider } from "@/components/ui/slider/slider";

Anatomy

One component: the parts are made for you.

<Slider
  label="Volume"
  description="Applies to every room."
  showValue
  defaultValue={40}
  marks={[{ value: 0, label: "0" }, { value: 100, label: "100" }]}
/>
PartRendered asNotes
Label and valuelabel, outputThe name at the left, and the number at the right.
TrackdivThe part that takes a press. It is taller than the bar, so it is easy to hit.
FilldivThe colored part of the bar: up to the thumb, or between the thumbs.
MarksspanTicks on the bar, with a label under each if you give one.
Thumbdiv and a range inputThe part that moves. The input is what a form and a screen reader use.
DescriptionpA line under the track that says more.

Keyboard

On a thumb that has focus.

KeyWhat it does
→ ↑Adds one step.
← ↓Takes one step.
Page Up, Page DownMoves by a bigger step (about a tenth of the range).
Home, EndGoes to the smallest or the biggest value.
TabMoves to the next thumb, or the next control.

Examples

Usage

Drag the thumb, press on the track, or use the arrow keys.

40

Range

Give it a list of numbers and it has a thumb for each. The number is written as a price here.

$200 – $800

From 200 to 800

Controlled

onChange runs as the thumb moves, to show the number. onChangeEnd runs when it is let go, to save it.

40

Now 40, saved when let go: 40

Marks

Marks with a label name the places on the track. marks on its own puts one at every step.

3

From the middle

origin is where the fill starts. On a slider from -50 to 50, 0 fills from the middle, to the left or the right.

20

Tooltip

A bubble with the number over the thumb while it is pointed at, held or focused.

Colors

30
45
60
75
90

Sizes

50
50
50

Vertical

A slider that stands up, for a mixer, a gain, a level.

65
35
20–70

In a form

Give it a name and the number goes with the form. A range sends one for each thumb, under the same name.

70
20–60

Disabled

40

Component API

Slider takes the props below. `value` and the functions have the shape of the value you give: a number, or a list.

PropTypeDefault
valuenumber | number[]-
defaultValuenumber | number[]minValue
onChange(value) => void-
onChangeEnd(value) => void-
minValuenumber0
maxValuenumber100
stepnumber1
labelReactNode-
descriptionReactNode-
showValuebooleanfalse
formatOptionsIntl.NumberFormatOptions-
orientation"horizontal" | "vertical""horizontal"
size"sm" | "md" | "lg""md"
color"primary" | "secondary" | "success" | "warning" | "danger""primary"
marksboolean | (number | { value, label })[]-
showTooltipbooleanfalse
originnumberminValue
showFillbooleantrue
thumbLabelsstring[]Minimum, Maximum
namestring-
isDisabledbooleanfalse
aria-labelstring"Slider"
classNamestring-