---
title: Slider
description: Choose a number or range by moving one or more thumbs.
package: moraine
version: 0.11.0
repository: https://github.com/subframe7536/moraine
---

# Slider

> Choose a number or range by moving one or more thumbs.

## Anatomy

```text
Slider [component; slot=root]
├── track [slot]
│   ├── range [slot]
│   └── marker [slot]
└── thumb [slot]
```

## Usage

Use Slider when a numeric value or range is best chosen spatially. Pair it with a labeled numeric
field when users need precise text entry. Use [NumberInput](https://moraine.subf.dev/components/number-input.md) when the value
is typed and stepped rather than dragged.
Use [BoldSlider](https://moraine.subf.dev/components/bold-slider.md) for a compact single value with the label and value
shown inside the track.

```tsx
import { Field, Slider } from 'moraine'

export function Example() {
  return (
    <Field label="Volume">
      <Slider defaultValue={50} />
    </Field>
  )
}
```

### Single values and ranges

Use a number for one thumb and an array for one thumb per entry, such as an ordered pair for a
range. Values are clamped to `min`–`max` (default `0`–`100`), and arrays are sorted. Pair `value`
with `onValueChange` for controlled state, or use `defaultValue` for uncontrolled state; its shape
sets the shape of the value that callbacks receive.

`onValueChange` fires on every change during a drag, track click, or key press, but not for
programmatic changes to `value`. Use `onValueCommit` to react once when the interaction ends, such
as when saving a setting.

```tsx
<Slider value={volume()} onValueChange={setVolume} />
<Slider value={range()} onValueChange={setRange} onValueCommit={saveRange} />
```

### Step and markers

Set `step` to snap pointer drag and keyboard navigation to multiples of it from `min`. Set `markers`
to `true` to draw a tick at each step (this requires a `step` above `0`), or to a number to draw a
tick every that many units without changing how the value snaps.

```tsx
<Slider value={value()} min={0} max={100} step={10} markers onValueChange={setValue} />
<Slider value={value()} min={0} max={100} markers={25} onValueChange={setValue} />
```

### Value text format

`formatOptions` accepts `Intl.NumberFormat` options and formats each thumb's `aria-valuetext` with
the provider locale. It does not change the value that callbacks receive. A `percent` style
multiplies by 100, so pair it with a `0`–`1` range. BoldSlider also uses `formatOptions` for its
visible value unless `valueLabel` is a formatter.

```tsx
<Slider defaultValue={50} formatOptions={{ style: 'unit', unit: 'percent' }} aria-label="Zoom" />
```

### Forms

Add `name` for native form submission, or place the slider inside `form.Field` from
[createForm](https://moraine.subf.dev/components/form.md) for schema binding. Use standalone [Field](https://moraine.subf.dev/components/field.md) when
you only need a label and messages.

```tsx
<Slider name="brightness" defaultValue={75} step={5} min={0} max={100} />
```

### Custom content

Pass `children` to render extra content inside the root after the thumbs. A render function
receives the live `value`, sorted `values`, `percentages` from `0` to `1`, `dragging` state, and the
`startEdge` where the filled range begins. Declare the function's parameter even when you do not use
it; a zero-argument function is called as an accessor and is not mounted as a component.

```tsx
<Slider defaultValue={40}>{(state) => <output>{state.value}</output>}</Slider>
```

### Keyboard interaction

When `step` is omitted, keyboard stepping defaults to 1% of the configured range. Page-sized
movement is approximately 10% of the range and is snapped to `step` when one is defined. Horizontal
arrow keys swap in right-to-left layouts, and a `reversed` vertical slider swaps <kbd>ArrowUp</kbd>
and <kbd>ArrowDown</kbd>.

| Key                                         | Description                                             |
| ------------------------------------------- | ------------------------------------------------------- |
| <kbd>ArrowRight</kbd> / <kbd>ArrowUp</kbd>  | Moves in the increasing direction by one keyboard step. |
| <kbd>ArrowLeft</kbd> / <kbd>ArrowDown</kbd> | Moves in the decreasing direction by one keyboard step. |
| <kbd>Shift + Arrow</kbd>                    | Moves by the page-sized increment.                      |
| <kbd>PageUp</kbd> / <kbd>PageDown</kbd>     | Moves by the page-sized increment.                      |
| <kbd>Home</kbd>                             | Moves the focused thumb to its minimum permitted value. |
| <kbd>End</kbd>                              | Moves the focused thumb to its maximum permitted value. |

## Examples

### Control output volume

Keep a single number in local state and update it from `onValueChange`. Mute can write `0` back
into the same signal.

```tsx
import { Button, Icon, Slider } from 'moraine'
import { createSignal } from 'solid-js'

export function ControlledSingle() {
  const [volume, setVolume] = createSignal(75)

  const volumeIcon = () => {
    if (volume() === 0) {
      return 'i-lucide:volume-x'
    }
    if (volume() < 50) {
      return 'i-lucide:volume-1'
    }
    return 'i-lucide:volume-2'
  }

  return (
    <div class="p-4 b-1 b-border rounded-xl max-w-md w-full space-y-2">
      <div class="flex items-center justify-between">
        <div class="flex gap-2 items-center">
          <Button
            variant="ghost"
            size="sm"
            class="p-0 size-8"
            onClick={() => setVolume((v) => (v === 0 ? 75 : 0))}
            aria-label="Mute / Unmute"
          >
            <Icon name={volumeIcon()} class="size-4" />
          </Button>
          <span class="text-sm font-medium">Output Volume</span>
        </div>
        <span class="text-xs text-primary font-mono font-semibold">{volume()}%</span>
      </div>

      <Slider value={volume()} min={0} max={100} step={1} onValueChange={setVolume} class="mb-2" />
    </div>
  )
}
```

### Set a numeric range

Pass an ordered pair for two thumbs. `minStepsBetweenThumbs` and `allowThumbCrossing` constrain
whether the thumbs may overlap.

```tsx
import { Checkbox, Slider } from 'moraine'
import { createSignal } from 'solid-js'

export function RangeSlider() {
  const [rangeValue, setRangeValue] = createSignal<number[]>([20, 75])
  const [minStepsBetweenThumbs, setMinStepsBetweenThumbs] = createSignal(0)
  const [allowThumbCrossing, setAllowThumbCrossing] = createSignal(true)

  return (
    <div class="max-w-xl space-y-3">
      <Checkbox
        checked={allowThumbCrossing()}
        onCheckedChange={setAllowThumbCrossing}
        label="Allow dragging across overlapping thumbs"
      />
      <Checkbox
        checked={minStepsBetweenThumbs() > 0}
        onCheckedChange={(isChecked) => setMinStepsBetweenThumbs(isChecked ? 10 : 0)}
        label="Min steps between thumbs"
      />
      <Slider
        value={rangeValue()}
        min={0}
        max={100}
        step={1}
        minStepsBetweenThumbs={minStepsBetweenThumbs()}
        allowThumbCrossing={allowThumbCrossing()}
        onValueChange={(next) => {
          if (Array.isArray(next)) {
            setRangeValue(next)
          }
        }}
      />
      <p class="text-xs text-muted-foreground w-50">
        Range: {rangeValue()[0]} - {rangeValue()[1]}
      </p>
      <p class="text-xs text-muted-foreground w-50">
        Thumb crossing:{' '}
        {allowThumbCrossing() && minStepsBetweenThumbs() === 0 ? 'Enabled' : 'Constrained'}
      </p>
      <p class="text-xs text-muted-foreground w-50">Min steps between: {minStepsBetweenThumbs()}</p>
    </div>
  )
}
```

### Bind brightness to a form

Place the slider in `form.Field` so the schema owns the committed number.

```tsx
import { Button, createForm, Slider } from 'moraine'
import type { SliderT } from 'moraine'
import { createSignal, untrack } from 'solid-js'
import * as v from 'valibot'

export function FormIntegration() {
  const [formState, setFormState] = createSignal({
    volume: 10,
  })

  const updateFormVolume = (nextValue: SliderT.Value) => {
    const next = Array.isArray(nextValue) ? (nextValue[0] ?? 0) : nextValue
    setFormState((prev) => ({ ...prev, volume: next }))
  }
  const form = createForm({
    schema: v.object({ volume: v.pipe(v.number(), v.minValue(20, 'Volume must be at least 20.')) }),
    initialInput: untrack(formState),
    validate: 'input',
  })

  return (
    <form.Form>
      <div class="max-w-xl space-y-4">
        <form.Field name="volume" label="Volume" description="Keep it at least 20.">
          <Slider value={formState().volume} onValueChange={updateFormVolume} />
        </form.Field>
        <div class="flex gap-3 items-center">
          <Button type="submit" variant="soft" tone="neutral" size="sm">
            Validate
          </Button>
          <p class="text-xs text-muted-foreground">Current volume: {formState().volume}</p>
        </div>
      </div>
    </form.Form>
  )
}
```

### Snap volume to ticks

Set `step` so drag and keyboard land on increments. Enable `markers` to draw those ticks on the
track.

```tsx
import { Slider } from 'moraine'
import { createSignal } from 'solid-js'

export function StepMarker() {
  const [value, setValue] = createSignal(40)
  const [range, setRange] = createSignal([20, 60])

  return (
    <div class="max-w-md w-full space-y-6">
      <div class="space-y-2">
        <div class="text-xs text-muted-foreground flex justify-between">
          <span>Stepped single (step = 10)</span>
          <span class="text-foreground font-mono">{value()}</span>
        </div>
        <Slider
          value={value()}
          min={0}
          max={100}
          step={10}
          markers
          onValueChange={(val) => {
            if (typeof val === 'number') {
              setValue(val)
            }
          }}
        />
      </div>

      <div class="space-y-2">
        <div class="text-xs text-muted-foreground flex justify-between">
          <span>Stepped range (step = 20)</span>
          <span class="text-foreground font-mono">
            {range()[0]} - {range()[1]}
          </span>
        </div>
        <Slider
          defaultValue={[20, 60]}
          value={range()}
          min={0}
          max={100}
          step={20}
          markers
          onValueChange={(val) => {
            if (Array.isArray(val)) {
              setRange(val)
            }
          }}
        />
      </div>
    </div>
  )
}
```

## API Reference

### Attributes

| Attributes | Slot | Description |
| --- | --- | --- |
| `data-disabled` | `slider`, `slider-thumb` | Present when the component, slot, or item is disabled. |
| `data-dragging` | `slider`, `slider-thumb` | Present while the related thumb or handle is being dragged. |
| `data-invalid` | `slider`, `slider-thumb` | Present when the field or form has a validation error. |
| `data-multiple` | `slider`, `slider-range` | Present when the control contains or selects multiple values. |
| `data-readonly` | `slider`, `slider-thumb` | Present when the field is in read-only mode. |
| `data-required` | `slider`, `slider-thumb` | Present when the field input is required. |
| `data-reversed` | `slider`, `slider-range`, `slider-thumb` | Present when the component direction or range is reversed. |
| `data-swipe-ignore` | `slider` | — |
| `data-empty` | `slider-range` | — |
| `data-active` | `slider-marker` | Present when the item or trigger is active. |
| `data-focus-visible` | `slider-thumb` | — |

### Props

Props for the Slider component.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| allowThumbCrossing | boolean \| undefined | true | Whether dragging can continue across another thumb when there is no minimum gap. When `false`,<br>a thumb stops at its neighbor. Ignored while `minStepsBetweenThumbs` is above `0`. |
| defaultValue | TValue \| undefined | — | The initial value (uncontrolled), with the same number or array shape as `value`; its shape<br>also sets the shape that `onValueChange` and `onValueCommit` receive. Defaults to `min`. |
| disabled | boolean \| undefined | false | Whether the control is disabled: it cannot be interacted with and sets `aria-disabled`.<br>When omitted, the control inherits `disabled` from the surrounding `Field`; an explicit<br>`false` overrides the `Field`. |
| form | string \| undefined | — | The id of a `<form>` the hidden inputs belong to, instead of the closest<br>ancestor form. |
| formatOptions | Intl.NumberFormatOptions \| undefined | — | `Intl.NumberFormat` options used to format values for `aria-valuetext`, such as<br>`{ style: 'percent' }`. Formatting uses the provider locale and does not change the<br>value passed to callbacks; `BoldSlider` also uses it for its displayed value. Remember that a<br>`percent` style multiplies by 100, so pair it with a `0`-`1` range. |
| id | string \| undefined | — | The ID of the control's main focusable element, which a surrounding `Field` label points to<br>with `for`. A unique ID is generated when omitted. The control's related parts (hidden<br>input, label, description) derive their IDs from it, so keep it unique on the page. |
| inputRef | Ref<HTMLInputElement> \| undefined | — | Receives the hidden `<input type="range">` of the first thumb. |
| markers | boolean \| number \| undefined | false | Visual markers on the track. `true` marks every `step` and needs a `step` greater than 0.<br>A number marks every that many units without affecting snapping. |
| max | number \| undefined | 100 | Maximum value of the slider. |
| min | number \| undefined | 0 | Minimum value of the slider. |
| minStepsBetweenThumbs | number \| undefined | 0 | Minimum distance between neighboring thumbs in a multi-thumb slider, counted in `step` units<br>(1% of the range when `step` is not set). A value above `0` also stops thumbs from crossing,<br>regardless of `allowThumbCrossing`. |
| name | string \| undefined | — | The name of the control, used for native form submission. When omitted, the control uses<br>the name of its form binding or a string `name` set on the surrounding `Field`. |
| onValueChange | ((value: TValue) => void) \| undefined | — | Called on every value change during interaction (pointer drag, track click, or key press),<br>with the new value in the same shape as `value`. Does not fire for programmatic changes to<br>`value`. Use `onValueCommit` to react once per finished interaction. |
| onValueCommit | ((value: TValue) => void) \| undefined | — | Called once an interaction that changed the value finishes: when the pointer is released,<br>when a navigation key is released, or when focus leaves the slider. Receives the final value in<br>the same shape as `value`. |
| orientation | 'horizontal' \| 'vertical' \| undefined | 'horizontal' | Direction of the track. A `vertical` slider fills the height of its parent and puts `min` at the bottom unless `reversed`. |
| readOnly | boolean \| undefined | false | Whether the control is read-only: the value is visible and focusable but cannot be changed,<br>and `aria-readonly` is set. When omitted, the control inherits `readOnly` from the<br>surrounding `Field`. |
| required | boolean \| undefined | false | Whether the control is required, which sets `aria-required` (and the native `required`<br>attribute where the control renders a native input). When omitted, the control inherits<br>`required` from the surrounding `Field`. |
| reversed | boolean \| undefined | false | Reverses the track direction, so `min` sits at the right (or top when vertical) instead of<br>the left (or bottom) in left-to-right layouts. |
| size | 'sm' \| 'md' \| 'lg' \| undefined | 'md' | Visual size of the component. |
| step | number \| undefined | — | Step increment between values; pointer and keyboard values snap to multiples of it from `min`.<br>When omitted (or not above `0`), pointer movement is continuous and arrow keys move by 1% of<br>the range. `PageUp`/`PageDown` and `Shift` + arrow move by about 10% of the range. |
| thumbAlignment | 'contain' \| 'overflow' \| undefined | 'overflow' | Visual alignment of the thumb at the track ends.<br>`'overflow'` centers the thumb on the value so half of it extends past<br>the track at `min` and `max`. `'contain'` clamps the thumb inside the<br>track so its edges stay within bounds. Value mapping is unaffected. |
| translations | Translations \| undefined | — | Localized message overrides for this slider instance: `thumb` returns each thumb's<br>`aria-label` and `valueText` returns its `aria-valuetext`. |
| value | TValue \| undefined | — | The current value (controlled). A number renders one thumb and an array renders one thumb per<br>entry (an empty array gives one thumb at `min`). Values are clamped to `min`-`max` and<br>arrays are sorted. Leave it `undefined` for uncontrolled usage. The slider throws a<br>`RangeError` when `max` is not greater than `min`. |
| children | JSX.Element \| Component<ChildrenRenderProps<TValue>> \| undefined | — | Content rendered inside the root after the thumbs, or a render function receiving the live slider state.<br>A render function must declare its parameter, even when unused. A zero-argument<br>function is called as an accessor and is not mounted as a component. |
| class | SlotClassValue \| undefined | — | Class applied to the component root or trigger element. |
| classes | Classes \| undefined | — | Family slot class defaults for this instance. |
| style | SlotStyleValue \| undefined | — | Style applied to the component root or trigger element. |
| styles | Styles \| undefined | — | Family slot style defaults for this instance. |

**`formatOptions` example**

```tsx
import { Slider } from 'moraine'

<Slider
  defaultValue={0.25}
  min={0}
  max={1}
  step={0.05}
  formatOptions={{ style: 'percent' }}
/>
```

**`onValueCommit` example**

```tsx
import { Slider } from 'moraine'

<Slider
  defaultValue={[20, 80]}
  onValueCommit={(range) => console.log(`${range[0]} to ${range[1]}`)}
/>
```

**`translations` example**

```tsx
import { Slider } from 'moraine'

<Slider
  defaultValue={[20, 80]}
  translations={{
    thumb: ({ index }) => (index === 0 ? 'Minimum price' : 'Maximum price'),
  }}
/>
```

**`children` example**

```tsx
import { Slider } from 'moraine'

<Slider defaultValue={30}>
  {(state) => <output>{state.dragging ? 'Dragging ' : ''}{state.values[0]}</output>}
</Slider>
```
