# or
yarn add @zag-js/slider @zag-js/react
```

## Anatomy

To set up the slider correctly, you'll need to understand its anatomy and how we
name its parts.

> Each part includes a `data-part` attribute to help identify them in the DOM.



## Usage

First, import the slider package into your project

```jsx
import * as slider from "@zag-js/slider"
```

The slider package exports two key functions:

- `machine` â The state machine logic for the slider widget as described in the
  WAI-ARIA spec.
- `connect` â The function that translates the machine's state to JSX attributes
  and event handlers.

> You'll need to provide a unique `id` to the `useMachine` hook. This is used to
> ensure that every part has a unique identifier.

Next, import the required hooks and functions for your framework and use the
slider machine in your project ð¥

```jsx
import * as slider from "@zag-js/slider"
import { useMachine, normalizeProps } from "@zag-js/react"

export function Slider() {
  const service = useMachine(slider.machine, { id: "1", value: [0] })

  const api = slider.connect(service, normalizeProps)

  return (
    <div {...api.getRootProps()}>
      <div>
        <label {...api.getLabelProps()}>Slider Label</label>
        <output {...api.getValueTextProps()}>{api.value.at(0)}</output>
      </div>
      <div {...api.getControlProps()}>
        <div {...api.getTrackProps()}>
          <div {...api.getRangeProps()} />
        </div>
        {api.value.map((_, index) => (
          <div key={index} {...api.getThumbProps({ index })}>
            <input {...api.getHiddenInputProps({ index })} />
          </div>
        ))}
      </div>
    </div>
  )
}
```

### Changing the orientation

By default, the slider is assumed to be horizontal. To change the orientation to
vertical, set the `orientation` property in the machine's context to `vertical`.

In this mode, the slider will use the arrow up and down keys to
increment/decrement its value.

> Don't forget to change the styles of the vertical slider by specifying its
> height

```jsx {2}
const service = useMachine(slider.machine, {
  orientation: "vertical",
})
```

### Setting the initial value

Pass the `defaultValue` property to the machine's context to set the initial
value.

```jsx {2}
const service = useMachine(slider.machine, {
  defaultValue: [30],
})
```

### Controlled slider

To control the slider's value programmatically, pass the `value` and
`onValueChange` properties.

```tsx
import { useState } from "react"

export function ControlledSlider() {
  const [value, setValue] = useState([30])

  const service = useMachine(slider.machine, {
    value,
    onValueChange(details) {
      setValue(details.value)
    },
  })

  return (
    // ...
  )
}

```

### Specifying the minimum and maximum

By default, the minimum is `0` and the maximum is `100`. If that's not what you
want, you can easily specify different bounds by changing the values of the min
and/or max attributes.

For example, to ask the user for a value between `-10` and `10`, you can use:

```jsx {2-3}
const service = useMachine(slider.machine, {
  min: -10,
  max: 10,
})
```

### Setting the value's granularity

By default, the granularity, is `1`, meaning that the value is always an
integer. You can change the step attribute to control the granularity.

For example, If you need a value between `5` and `10`, accurate to two decimal
places, you should set the value of step to `0.01`:

```jsx {4}
const service = useMachine(slider.machine, {
  min: 5,
  max: 10,
  step: 0.01,
})
```

### Listening for changes

When the slider value changes, the `onValueChange` and `onValueChangeEnd`
callbacks are invoked. You can use this to setup custom behaviors in your app.

```jsx {2-7}
const service = useMachine(slider.machine, {
  onValueChange(details) {
    console.log("value is changing to:", details)
  },
  onValueChangeEnd(details) {
    console.log("value has changed to:", details)
  },
})
```

### Changing the start position

By default, the slider's origin is at the `start` position (left in LTR and
right in RTL). Change it by setting the `origin` property to these values:

- `start`: the track will be filled from start to the thumb (default).
- `center`: the track will be filled from the center (50%) to the thumb.
- `end`: the track will be filled from the thumb to the end.

This applies to sliders with single values.

In scenarios where the value represents an offset (or relative value) on a
diverging scale, it might be useful to change the origin to center. To do this,
set the `origin` context property to `center`.

```jsx {2}
const service = useMachine(slider.machine, {
  origin: "center",
})
```

In scenarios where the slider value is used as a threshold to include values
above it, it might make more sense to set the `origin` to `end` to have the
track filled from the thumb to the end.

### Changing the thumb alignment

By default, the thumb is aligned to the start of the track. Set the
`thumbAlignment` context property to `contain` or `center`.

- `center`: the thumb will extend beyond the bounds of the slider track.
- `contain`: the thumb will be contained within the bounds of the track.

```jsx {2}
const service = useMachine(slider.machine, {
  thumbAlignment: "center",
})
```

If you use `contain` alignment, you might need to set the thumb size to prevent
any flickering.

```jsx {3}
const service = useMachine(slider.machine, {
  thumbAlignment: "contain",
  thumbSize: { width: 20, height: 20 },
})
```

### Usage within forms

To use slider within forms, use the exposed `inputProps` from the `connect`
function and ensure you pass `name` value to the machine's context. It will
render a hidden input and ensure the value changes get propagated to the form
correctly.

```jsx {2}
const service = useMachine(slider.machine, {
  name: "quantity",
})
```

### RTL Support

The slider has built-in support for RTL alignment and interaction. In the RTL
mode, operations are performed from right to left, meaning, the left arrow key
will increment and the right arrow key will decrement.

To enable RTL support, pass the `dir: rtl` context property

```jsx {2}
const service = useMachine(slider.machine, {
  dir: "rtl",
})
```

> While we take care of the interactions in RTL mode, you'll have to ensure you
> apply the correct CSS styles to flip the layout.

### Using slider marks

To show marks or ticks along the slider track, use the exposed
`api.getMarkerProps()` method to position the slider marks relative to the
track.

```jsx {11-15}
//...
<div>
  <div {...api.getControlProps()}>
    <div {...api.getTrackProps()}>
      <div {...api.getRangeProps()} />
    </div>
    {api.value.map((_, index) => (
      <div key={index} {...api.getThumbProps({ index })}>
        <input {...api.getHiddenInputProps({ index })} />
      </div>
    ))}
  </div>
  <div {...api.getMarkerGroupProps()}>
    <span {...api.getMarkerProps({ value: 10 })}>|</span>
    <span {...api.getMarkerProps({ value: 30 })}>|</span>
    <span {...api.getMarkerProps({ value: 90 })}>|</span>
  </div>
</div>
//...
```

## Styling guide

Earlier, we mentioned that each slider part has a `data-part` attribute added to
them to select and style them in the DOM.

### Focused State

When the slider thumb is focused, the `data-focus` attribute is added to the
root, control, thumb and label parts.

```css
[data-part="root"][data-focus] {
  /* styles for root focus state */
}

[data-part="thumb"]:focus {
  /* styles for thumb focus state */
}

[data-part="control"][data-focus] {
  /* styles for control focus state */
}

[data-part="track"][data-focus] {
  /* styles for track focus state */
}

[data-part="range"][data-focus] {
  /* styles for range focus state */
}
```

### Disabled State

When the slider is disabled, the `data-disabled` attribute is added to the root,
label, control and thumb.

```css
[data-part="root"][data-disabled] {
  /* styles for root disabled state */
}

[data-part="label"][data-disabled] {
  /* styles for label disabled state */
}

[data-part="control"][data-disabled] {
  /* styles for control disabled state */
}

[data-part="value-text"][data-disabled] {
  /* styles for output disabled state */
}

[data-part="thumb"][data-disabled] {
  /* styles for thumb disabled state */
}

[data-part="range"][data-disabled] {
  /* styles for thumb disabled state */
}
```

### Invalid State

When the slider is invalid, the `data-invalid` attribute is added to the root,
track, range, label, and thumb parts.

```css
[data-part="root"][data-invalid] {
  /* styles for root invalid state */
}

[data-part="label"][data-invalid] {
  /* styles for label invalid state */
}

[data-part="control"][data-invalid] {
  /* styles for control invalid state */
}

[data-part="valueText"][data-invalid] {
  /* styles for output invalid state */
}

[data-part="thumb"][data-invalid] {
  /* styles for thumb invalid state */
}

[data-part="range"][data-invalid] {
  /* styles for range invalid state */
}
```

### Orientation

```css
[data-part="root"][data-orientation="(horizontal|vertical)"] {
  /* styles for horizontal or vertical  */
}

[data-part="thumb"][data-orientation="(horizontal|vertical)"] {
  /* styles for horizontal or vertical  */
}

[data-part="track"][data-orientation="(horizontal|vertical)"] {
  /* styles for horizontal or vertical  */
}
```

### Styling the markers

```css
[data-part="marker"][data-state="(at|under|over)-value"] {
  /* styles for when the value exceeds the marker's value */
}
```

## Methods and Properties

### Machine Context

The slider machine exposes the following context properties:

**`ids`**
Type: `Partial<{ root: string; thumb: (index: number) => string; hiddenInput: (index: number) => string; control: string; track: string; range: string; label: string; valueText: string; marker: (index: number) => string; }>`
Description: The ids of the elements in the slider. Useful for composition.

**`aria-label`**
Type: `string[]`
Description: The aria-label of each slider thumb. Useful for providing an accessible name to the slider

**`aria-labelledby`**
Type: `string[]`
Description: The `id` of the elements that labels each slider thumb. Useful for providing an accessible name to the slider

**`name`**
Type: `string`
Description: The name associated with each slider thumb (when used in a form)

**`form`**
Type: `string`
Description: The associate form of the underlying input element.

**`value`**
Type: `number[]`
Description: The controlled value of the slider

**`defaultValue`**
Type: `number[]`
Description: The initial value of the slider when rendered.
Use when you don't need to control the value of the slider.

**`disabled`**
Type: `boolean`
Description: Whether the slider is disabled

**`readOnly`**
Type: `boolean`
Description: Whether the slider is read-only

**`invalid`**
Type: `boolean`
Description: Whether the slider is invalid

**`onValueChange`**
Type: `(details: ValueChangeDetails) => void`
Description: Function invoked when the value of the slider changes

**`onValueChangeEnd`**
Type: `(details: ValueChangeDetails) => void`
Description: Function invoked when the slider value change is done

**`onFocusChange`**
Type: `(details: FocusChangeDetails) => void`
Description: Function invoked when the slider's focused index changes

**`getAriaValueText`**
Type: `(details: ValueTextDetails) => string`
Description: Function that returns a human readable value for the slider thumb

**`min`**
Type: `number`
Description: The minimum value of the slider

**`max`**
Type: `number`
Description: The maximum value of the slider

**`step`**
Type: `number`
Description: The step value of the slider

**`minStepsBetweenThumbs`**
Type: `number`
Description: The minimum permitted steps between multiple thumbs.

`minStepsBetweenThumbs` * `step` should reflect the gap between the thumbs.

- `step: 1` and `minStepsBetweenThumbs: 10` => gap is `10`
- `step: 10` and `minStepsBetweenThumbs: 2` => gap is `20`

**`orientation`**
Type: `"vertical" | "horizontal"`
Description: The orientation of the slider

**`origin`**
Type: `"start" | "center" | "end"`
Description: The origin of the slider range. The track is filled from the origin
to the thumb for single values.
- "start": Useful when the value represents an absolute value
- "center": Useful when the value represents an offset (relative)
- "end": Useful when the value represents an offset from the end

**`thumbAlignment`**
Type: `"center" | "contain"`
Description: The alignment of the slider thumb relative to the track
- `center`: the thumb will extend beyond the bounds of the slider track.
- `contain`: the thumb will be contained within the bounds of the track.

**`thumbSize`**
Type: `{ width: number; height: number; }`
Description: The slider thumbs dimensions

**`dir`**
Type: `"ltr" | "rtl"`
Description: The document's text/writing direction.

**`id`**
Type: `string`
Description: The unique identifier of the machine.

**`getRootNode`**
Type: `() => ShadowRoot | Node | Document`
Description: A root node to correctly resolve document in custom environments. E.x.: Iframes, Electron.

### Machine API

The slider `api` exposes the following methods:

**`value`**
Type: `number[]`
Description: The value of the slider.

**`dragging`**
Type: `boolean`
Description: Whether the slider is being dragged.

**`focused`**
Type: `boolean`
Description: Whether the slider is focused.

**`setValue`**
Type: `(value: number[]) => void`
Description: Function to set the value of the slider.

**`getThumbValue`**
Type: `(index: number) => number`
Description: Returns the value of the thumb at the given index.

**`setThumbValue`**
Type: `(index: number, value: number) => void`
Description: Sets the value of the thumb at the given index.

**`getValuePercent`**
Type: `(value: number) => number`
Description: Returns the percent of the thumb at the given index.

**`getPercentValue`**
Type: `(percent: number) => number`
Description: Returns the value of the thumb at the given percent.

**`getThumbPercent`**
Type: `(index: number) => number`
Description: Returns the percent of the thumb at the given index.

**`setThumbPercent`**
Type: `(index: number, percent: number) => void`
Description: Sets the percent of the thumb at the given index.

**`getThumbMin`**
Type: `(index: number) => number`
Description: Returns the min value of the thumb at the given index.

**`getThumbMax`**
Type: `(index: number) => number`
Description: Returns the max value of the thumb at the given index.

**`increment`**
Type: `(index: number) => void`
Description: Function to increment the value of the slider at the given index.

**`decrement`**
Type: `(index: number) => void`
Description: Function to decrement the value of the slider at the given index.

**`focus`**
Type: `VoidFunction`
Description: Function to focus the slider. This focuses the first thumb.

### Data Attributes

**`Label`**

**`data-scope`**: slider
**`data-part`**: label
**`data-disabled`**: Present when disabled
**`data-orientation`**: The orientation of the label
**`data-invalid`**: Present when invalid
**`data-dragging`**: Present when in the dragging state
**`data-focus`**: Present when focused

**`Root`**

**`data-scope`**: slider
**`data-part`**: root
**`data-disabled`**: Present when disabled
**`data-orientation`**: The orientation of the slider
**`data-dragging`**: Present when in the dragging state
**`data-invalid`**: Present when invalid
**`data-focus`**: Present when focused

**`ValueText`**

**`data-scope`**: slider
**`data-part`**: value-text
**`data-disabled`**: Present when disabled
**`data-orientation`**: The orientation of the valuetext
**`data-invalid`**: Present when invalid
**`data-focus`**: Present when focused

**`Track`**

**`data-scope`**: slider
**`data-part`**: track
**`data-disabled`**: Present when disabled
**`data-invalid`**: Present when invalid
**`data-dragging`**: Present when in the dragging state
**`data-orientation`**: The orientation of the track
**`data-focus`**: Present when focused

**`Thumb`**

**`data-scope`**: slider
**`data-part`**: thumb
**`data-index`**: The index of the item
**`data-name`**: 
**`data-disabled`**: Present when disabled
**`data-orientation`**: The orientation of the thumb
**`data-focus`**: Present when focused
**`data-dragging`**: Present when in the dragging state

**`Range`**

**`data-scope`**: slider
**`data-part`**: range
**`data-dragging`**: Present when in the dragging state
**`data-focus`**: Present when focused
**`data-invalid`**: Present when invalid
**`data-disabled`**: Present when disabled
**`data-orientation`**: The orientation of the range

**`Control`**

**`data-scope`**: slider
**`data-part`**: control
**`data-dragging`**: Present when in the dragging state
**`data-disabled`**: Present when disabled
**`data-orientation`**: The orientation of the control
**`data-invalid`**: Present when invalid
**`data-focus`**: Present when focused

**`MarkerGroup`**

**`data-scope`**: slider
**`data-part`**: marker-group
**`data-orientation`**: The orientation of the markergroup

**`Marker`**

**`data-scope`**: slider
**`data-part`**: marker
**`data-orientation`**: The orientation of the marker
**`data-value`**: The value of the item
**`data-disabled`**: Present when disabled
**`data-state`**: 

**`DraggingIndicator`**

**`data-scope`**: slider
**`data-part`**: dragging-indicator
**`data-orientation`**: The orientation of the draggingindicator
**`data-state`**: "open" | "closed"

### CSS Variables

<CssVarTable name="slider" />

## Accessibility

Adheres to the
[Slider WAI-ARIA design pattern](https://www.w3.org/WAI/ARIA/apg/patterns/slider).

### Keyboard Interactions

**`ArrowRight`**
Description: <span>Increments the slider based on defined step</span>

**`ArrowLeft`**
Description: <span>Decrements the slider based on defined step</span>

**`ArrowUp`**
Description: <span>Increases the value by the step amount.</span>

**`ArrowDown`**
Description: <span>Decreases the value by the step amount.</span>

**`PageUp`**
Description: <span>Increases the value by a larger step</span>

**`PageDown`**
Description: <span>Decreases the value by a larger step</span>

**`Shift + ArrowUp`**
Description: <span>Increases the value by a larger step</span>

**`Shift + ArrowDown`**
Description: <span>Decreases the value by a larger step</span>

**`Home`**
Description: Sets the value to its minimum.

**`End`**
Description: Sets the value to its maximum.
A range slider is a multi-thumb slider used to select a range between two
numbers.

## Resources


[Latest version: v1.33.1](https://www.npmjs.com/package/@zag-js/slider)
[Logic Visualizer](https://zag-visualizer.vercel.app/slider)
[Source Code](https://github.com/chakra-ui/zag/tree/main/packages/machines/slider)



**Features**

- Fully managed keyboard navigation
- Supports touch or click on track to update value
- Supports Right-to-Left directionality
- Support for horizontal and vertical orientations
- Prevents text selection while dragging

## Installation

To use the range slider machine in your project, run the following command in
your command line:

```bash
npm install @zag-js/slider @zag-js/react