Skip to content
Shaken UI
Sign in

Slider

Save

A single or range slider with a value readout, a value bubble on the thumb, labeled marks, and keyboard steps.

Category
Forms
Version
0.1.0
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Slider preview
Temperature
0.7
Monthly budget
$200 โ€“ $1,200
Context window
64k tokens

Installation

npx @shakenui/cli add slider

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add slider --dry-run

Usage

slider-example.tsx
"use client";

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

export default function SliderExample() {
  return (
    <div className="grid w-full max-w-sm gap-9">
      <Slider
        label="Temperature"
        defaultValue={0.7}
        min={0}
        max={2}
        step={0.1}
        largeStep={0.5}
        formatValue={(value) => value.toFixed(1)}
        marks={[
          { value: 0, label: "Precise" },
          { value: 1, label: "Balanced" },
          { value: 2, label: "Creative" },
        ]}
      />
      <Slider
        label="Monthly budget"
        defaultValue={[200, 1200]}
        min={0}
        max={2000}
        step={50}
        largeStep={250}
        minStepsBetweenValues={2}
        format={{ style: "currency", currency: "USD", maximumFractionDigits: 0 }}
        thumbLabels={["Minimum budget", "Maximum budget"]}
      />
      <Slider label="Context window" defaultValue={64} max={200} formatValue={(value) => `${value}k tokens`} disabled />
    </div>
  );
}

API

PropTypeDefaultDescription
value / defaultValuenumber | number[]โ€”A number for one thumb, an array for a range.
onValueChange / onValueCommitted(value) => voidโ€”Called while dragging and when the change is final.
min / max / stepnumber0 / 100 / 1Range and granularity.
largeStepnumber10Step for Shift + arrow and Page Up/Down.
labelReactNodeโ€”Visible label above the track; it names every thumb.
showValuebooleantrue with a labelShows the current value or range at the end of the label row.
tooltip"auto" | "always" | "never""auto"A value bubble over the thumb on hover, keyboard focus, and drag.
format / formatValueIntl.NumberFormatOptions | (value) => stringโ€”How values are written in the readout and the bubble.
marks{ value: number; label?: ReactNode }[]โ€”Labeled positions under the track.
thumbLabelsstring[]โ€”Accessible names for the thumbs of a range slider.

Accessibility

  • Each thumb holds a native <input type="range">, so screen readers announce its value and range.
  • Arrow keys move by step, Shift + arrow and Page Up/Down by largeStep, Home and End jump to the ends.
  • Slider.Label names single thumbs; range thumbs take thumbLabels as aria-label.
  • The value bubble and marks are aria-hidden duplicates of the announced value.
  • The thumb follows the pointer without easing; the bubble only fades under reduced motion.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/ui/slider.tsxslider
  • npm packages: @base-ui/react@^1.9.0React and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/slider/0.1.0.json.

ui/slider.tsxShow
ui/slider.tsx
"use client";

import { Slider as BaseSlider } from "@base-ui/react/slider";
import type { ReactNode } from "react";

type ClassName<State> = string | ((state: State) => string | undefined) | undefined;

function cx(...classes: (string | false | null | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}

/** Prepends base classes while keeping Base UI's state-function form of className working. */
function withBase<State>(base: string, className: ClassName<State>) {
  return typeof className === "function" ? (state: State) => cx(base, className(state)) : cx(base, className);
}

export interface SliderMark {
  /** Where the mark sits, in the slider's own units. */
  value: number;
  /** Text under the track. Leave it out for an unlabeled tick. */
  label?: ReactNode;
}

export interface SliderProps<Value extends number | readonly number[]> extends Omit<BaseSlider.Root.Props<Value>, "children"> {
  /** Visible label above the track. It names every thumb. */
  label?: ReactNode;
  /** Shows the current value (or range) at the end of the label row. */
  showValue?: boolean;
  /**
   * A small bubble above each thumb with its value. `auto` shows it while the thumb is hovered,
   * focused from the keyboard, or dragged; `always` keeps it up; `never` hides it.
   */
  tooltip?: "auto" | "always" | "never";
  /** Formats values for the readout and the tooltip. Defaults to `Intl.NumberFormat` with `format`. */
  formatValue?: (value: number) => string;
  /** Labeled positions under the track, such as the ends of a scale or common presets. */
  marks?: SliderMark[];
  /** Accessible names for the thumbs of a range slider, in order, such as `["Minimum", "Maximum"]`. */
  thumbLabels?: string[];
}

/**
 * A single or range slider. Pass a number for one thumb or an array for a range. Arrow keys move
 * by `step`, Shift + arrow and Page Up/Down by `largeStep`, Home and End jump to the ends.
 * The thumb follows the pointer without easing; only its press scale and the tooltip animate.
 */
export function Slider<Value extends number | readonly number[]>({
  label,
  showValue = label != null,
  tooltip = "auto",
  formatValue,
  marks,
  thumbLabels,
  min = 0,
  max = 100,
  format,
  locale,
  value,
  defaultValue,
  className,
  ...props
}: SliderProps<Value>) {
  const initial = value ?? defaultValue;
  const thumbCount = Array.isArray(initial) ? initial.length : 1;
  const formatter = new Intl.NumberFormat(locale, format);
  const display = formatValue ?? ((n: number) => formatter.format(n));
  const percent = (n: number) => ((n - min) / (max - min)) * 100;

  return (
    <BaseSlider.Root<Value>
      min={min}
      max={max}
      format={format}
      locale={locale}
      value={value}
      defaultValue={defaultValue}
      className={withBase("grid w-full gap-2.5 data-[disabled]:opacity-50", className)}
      {...props}
    >
      {label != null || showValue ? (
        <div className="flex items-baseline justify-between gap-4">
          {label != null ? (
            <BaseSlider.Label className="text-sm leading-5 font-medium text-zinc-950 select-none dark:text-white">
              {label}
            </BaseSlider.Label>
          ) : (
            <span />
          )}
          {showValue ? (
            <BaseSlider.Value aria-live="off" className="font-mono text-xs text-zinc-500 tabular-nums dark:text-zinc-400">
              {(_formatted, values) => values.map(display).join(" โ€“ ")}
            </BaseSlider.Value>
          ) : null}
        </div>
      ) : null}
      <BaseSlider.Control className="relative flex h-5 w-full cursor-pointer touch-none items-center select-none data-[disabled]:cursor-not-allowed">
        <BaseSlider.Track className="relative h-1 w-full rounded-full bg-zinc-950/10 dark:bg-white/15">
          <BaseSlider.Indicator className="rounded-full bg-zinc-950 dark:bg-white" />
          {Array.from({ length: thumbCount }, (_, index) => (
            <BaseSlider.Thumb
              key={index}
              index={index}
              aria-label={thumbLabels?.[index]}
              className={cx(
                "group/thumb relative size-4 rounded-full outline-none",
                "border border-zinc-950/20 bg-white shadow-[0_1px_3px_rgb(0_0_0/0.18)]",
                "dark:border-white dark:shadow-[0_0_0_3px_rgb(0_0_0),0_1px_3px_rgb(0_0_0/0.5)]",
                "transition-[scale,box-shadow] duration-150 ease-out motion-reduce:transition-none",
                "motion-safe:data-[dragging]:scale-110",
                "has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-sky-500",
                // A larger invisible hit area around the 16px thumb.
                "after:absolute after:-inset-2 after:rounded-full after:content-['']",
              )}
              render={(thumbProps, state) => (
                <div {...thumbProps}>
                  {thumbProps.children}
                  {tooltip === "never" ? null : (
                    <span
                      aria-hidden="true"
                      className={cx(
                        "pointer-events-none absolute bottom-full left-1/2 mb-2.5 -translate-x-1/2 origin-bottom",
                        "rounded-md px-1.5 py-1 font-mono text-[11px] leading-none whitespace-nowrap tabular-nums",
                        "bg-zinc-950 text-white shadow-[0_4px_12px_-4px_rgb(0_0_0/0.3)] dark:bg-white dark:text-black",
                        "transition-[opacity,scale] duration-150 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none",
                        tooltip === "always"
                          ? "opacity-100"
                          : cx(
                              "opacity-0 motion-safe:scale-90",
                              "group-hover/thumb:opacity-100 group-hover/thumb:scale-100",
                              "group-has-[:focus-visible]/thumb:opacity-100 group-has-[:focus-visible]/thumb:scale-100",
                              "group-data-[dragging]/thumb:opacity-100 group-data-[dragging]/thumb:scale-100",
                            ),
                      )}
                    >
                      {display(state.values[index] ?? min)}
                    </span>
                  )}
                </div>
              )}
            />
          ))}
        </BaseSlider.Track>
      </BaseSlider.Control>
      {marks?.length ? (
        <div aria-hidden="true" className="relative h-4">
          {marks.map((mark) => (
            <span
              key={mark.value}
              style={{ left: `${percent(mark.value)}%` }}
              className={cx(
                "absolute top-0 text-xs leading-none whitespace-nowrap text-zinc-500 tabular-nums dark:text-zinc-500",
                // Labels at the ends align to the track's edges instead of hanging past them.
                mark.value <= min ? "translate-x-0" : mark.value >= max ? "-translate-x-full" : "-translate-x-1/2",
              )}
            >
              {mark.label}
            </span>
          ))}
        </div>
      ) : null}
    </BaseSlider.Root>
  );
}