# react-ranger

> Hooks for building range and multi-range sliders in React

Latest version **2.1.0** (published 2020-09-11) · MIT license · 0 weekly downloads

## Install

```sh
npm install react-ranger
pnpm add react-ranger
yarn add react-ranger
bun add react-ranger
```

## Health

**Score 38/100 (D)** — status: abandoned.

Positive: has types package; esm support; no vulnerabilities; high quality score.

Warnings: low downloads.

Negative: abandoned.

## Facts

| | |
|---|---|
| Version | 2.1.0 |
| Published | 2020-09-11 |
| First published | 2014-06-08 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | separate (@types/react-ranger) |
| Module format | ESM + CommonJS |
| Dependencies | 0 |
| Unpacked size | 121.7 KB |
| Known vulnerabilities | 0 |
| Install scripts | yes |
| GitHub stars | 838 |
| Author | tannerlinsley |
| Maintainers | tannerlinsley |

## Links

- npm: https://www.npmjs.com/package/react-ranger
- Repository: https://github.com/tannerlinsley/react-ranger
- Homepage: https://github.com/tannerlinsley/react-ranger#readme
- Issues: https://github.com/tannerlinsley/react-ranger/issues
- npm.io page: https://npm.io/package/react-ranger

## Recent versions

- 2.1.0 (latest) — 2020-09-11
- 2.0.3 — 2020-06-30
- 2.0.2 — 2020-06-09
- 2.0.1 — 2020-06-09
- 2.0.0 — 2020-06-09
- 1.0.5 — 2018-06-24
- 1.0.4 — 2018-06-24
- 1.0.3 — 2018-06-24
- 1.0.2 — 2018-06-23
- 1.0.1 — 2018-06-23
- 1.0.0 — 2018-06-23
- 0.5.5 — 2015-01-15
- 0.5.4 — 2014-10-07
- 0.5.3 — 2014-10-06
- 0.5.2 — 2014-09-04
- … 10 more at https://npm.io/package/react-ranger/versions

## README

![React Ranger Header](https://github.com/tannerlinsley/react-ranger/raw/master/media/header.png)

<img src='https://github.com/tannerlinsley/react-ranger/raw/master/media/logo.png' width='300'/>

Hooks for building range and multi-range sliders in React

<a href="https://twitter.com/search?q=%23TanStack" target="\_parent">
  <img alt="#TanStack" src="https://img.shields.io/twitter/url?color=%2308a0e9&label=%23TanStack&style=social&url=https%3A%2F%2Ftwitter.com%2Fintent%2Ftweet%3Fbutton_hashtag%3DTanStack">
</a><a href="https://github.com/tannerlinsley/react-ranger/actions?query=workflow%3A%22react-ranger+tests%22">
<img src="https://github.com/tannerlinsley/react-ranger/workflows/react-ranger%20tests/badge.svg" />
</a><a href="https://npmjs.com/package/react-ranger" target="\_parent">
  <img alt="" src="https://img.shields.io/npm/dm/react-ranger.svg" />
</a><a href="https://bundlephobia.com/result?p=react-ranger@latest" target="\_parent">
  <img alt="" src="https://badgen.net/bundlephobia/minzip/react-ranger@latest" />
</a><a href="#badge">
    <img alt="semantic-release" src="https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg">
  </a><a href="https://github.com/tannerlinsley/react-ranger/discussions">
  <img alt="Join the discussion on Github" src="https://img.shields.io/badge/Github%20Discussions%20%26%20Support-Chat%20now!-blue" />
</a><a href="https://github.com/tannerlinsley/react-ranger" target="\_parent">
  <img alt="" src="https://img.shields.io/github/stars/tannerlinsley/react-ranger.svg?style=social&label=Star" />
</a><a href="https://twitter.com/tannerlinsley" target="\_parent">
  <img alt="" src="https://img.shields.io/twitter/follow/tannerlinsley.svg?style=social&label=Follow" />
</a>

Enjoy this library? Try them all! [React Table](https://github.com/tannerlinsley/react-table), [React Query](https://github.com/tannerlinsley/react-query), [React Form](https://github.com/tannerlinsley/react-form), [React Charts](https://github.com/tannerlinsley/react-charts)

<p align="center">
  <img src='https://github.com/tannerlinsley/react-ranger/raw/master/media/screenshot.png' width="700"/>
</p>

## Quick Features

- Headless!
- Single or Multiple Handles
- Handle Devider Items
- Custom Steps or Step-Size
- Custom Ticks
- <a href="https://bundlephobia.com/result?p=react-ranger@latest" target="\_parent">
  <img alt="" src="https://badgen.net/bundlephobia/minzip/react-ranger@latest" />
  </a>

## Examples

- Basic - [CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-ranger/tree/master/examples/basic) - [Source](./examples/basic)
- Multi-Range - [CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-ranger/tree/master/examples/multi-range) - [Source](./examples/multi-range)
- Custom Steps - [CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-ranger/tree/master/examples/custom-steps) - [Source](./examples/custom-steps)
- Custom Styles - [CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-ranger/tree/master/examples/custom-styles) - [Source](./examples/custom-styles)
- Update On Drag - [CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-ranger/tree/master/examples/update-on-drag) - [Source](./examples/update-on-drag)

## Sponsors

This library is being built and maintained by me, @tannerlinsley and I am always in need of more support to keep projects like this afloat. If you would like to get premium support, add your logo or name on this README, or simply just contribute to my open source Sponsorship goal, [visit my Github Sponsors page!](https://github.com/sponsors/tannerlinsley/)

[![Diamond Sponsors](https://raw.githubusercontent.com/tannerlinsley/files/master/sponsorships/diamond.png)](https://github.com/sponsors/tannerlinsley)

<table>
  <tbody>
    <tr>
      <td>
        <a href="https://github.com/sponsors/tannerlinsley" target="_blank">
          Get Your Logo Here!
        </a>
      </td>
    </tr>
  </tbody>
</table>

[![Gold Sponsors](https://raw.githubusercontent.com/tannerlinsley/files/master/sponsorships/gold.png)](https://github.com/sponsors/tannerlinsley)

<table>
  <tbody>
    <tr>
      <td>
        <a href="https://github.com/sponsors/tannerlinsley" target="_blank">
          Get Your Logo Here!
        </a>
      </td>
    </tr>
  </tbody>
</table>

[![Silver Sponsors](https://raw.githubusercontent.com/tannerlinsley/files/master/sponsorships/silver.png)](https://github.com/sponsors/tannerlinsley)

<table>
  <tbody>
    <tr>
       <td>
        <a href="https://github.com/sponsors/tannerlinsley" target="_blank">
          Get Your Logo Here!
        </a>
      </td>
    </tr>
  </tbody>
</table>

[![Bronze Sponsors](https://raw.githubusercontent.com/tannerlinsley/files/master/sponsorships/bronze.png)](https://github.com/sponsors/tannerlinsley)

<table>
  <tbody>
    <tr>
      <td>
        <a href="https://nozzle.io" target="_blank">
          <img width='150' src="https://nozzle.io/img/logo-blue.png">
        </a>
      </td>
    </tr>
  </tbody>
</table>

[![Supporters](https://raw.githubusercontent.com/tannerlinsley/files/master/sponsorships/supporters.png)](https://github.com/sponsors/tannerlinsley)

- Get your [name and link](#) here!

[![Fans](https://raw.githubusercontent.com/tannerlinsley/files/master/sponsorships/fans.png)](https://github.com/sponsors/tannerlinsley)

- Get your name here!

### [Become a Sponsor](https://github.com/sponsors/tannerlinsley/)

# Documentation

<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->


- [Installation](#installation)
  - [Sample Usage](#sample-usage)
  - [Options](#options)
  - [Returns](#returns)
  - [Interpolation](#interpolation)
- [Contributors ✨](#contributors-)

<!-- END doctoc generated TOC please keep comment here to allow auto update -->

# Installation

```bash
$ npm i --save react-ranger
# or
$ yarn add react-ranger
```

## Sample Usage

The following is a very basic example of a single range input that looks similar to Chrome's default appearance.

```javascript
import ReactRanger from 'react-ranger'

function App() {
  const [values, setValues] = React.useState([10])

  const { getTrackProps, handles } = useRanger({
    values,
    onChange: setValues,
    min: 0,
    max: 100,
    stepSize: 5,
  })

  return (
    <>
      <div
        {...getTrackProps({
          style: {
            height: '4px',
            background: '#ddd',
            boxShadow: 'inset 0 1px 2px rgba(0,0,0,.6)',
            borderRadius: '2px',
          },
        })}
      >
        {handles.map(({ getHandleProps }) => (
          <div
            {...getHandleProps({
              style: {
                width: '12px',
                height: '12px',
                borderRadius: '100%',
                background: 'linear-gradient(to bottom, #eee 45%, #ddd 55%)',
                border: 'solid 1px #888',
              },
            })}
          />
        ))}
      </div>
    </>
  )
}
```

## Options

- `value: Array<number>` - The current value (or values) for the range
  - **Required**
- `min: number` - The minimum limit for the range
  - **Required**
- `max: number` - The maximum limit for the range
  - **Required**
- `stepSize: number` - The distance between selectable steps
  - **Required**
- `steps: arrayOf(number)` - An array of custom steps to use. This will override `stepSize`,
- `tickSize: number`
- `ticks: arrayOf(number): Default: 10` - An array of custom ticks to use. This will override `tickSize`,
- `onChange: Function(newValue)` - A function that is called when the handle is released
- `onDrag: Function(newValue)` - A function that is called when a handled is dragged
- `interpolator: { getPercentageForValue: Function(value) => decimal, getValueForClientX: Function(x) => value}`
  - The Interpolator to use
  - Defualts to the bundled linear-scale interpolator
    See the [Interpolation section](#interpolation) for more info

## Returns

`useRanger` returns an `object` with the following properties:

- `getTrackProps(userProps): func` - A function that takes optional props and returns the combined necessary props for the track component.
- `ticks: array` - Ticks to be rendered. Each `tick` has the following props:
  - `value: number` - The tick number to be displayed
  - `getTickProps(userProps): func` - A function that take optional props and returns the combined necessary props for the tick component.
- `segments: array` - Segments to be rendered. Each `segment` has the following props:
  - `value: number` - The segments ending value
  - `getSegmentProps(userProps): func` - A function that take optional props and returns the combined necessary props for the segment component.
- `handles: array` - Handles to be rendered. Each `handle` has the following props:
  - `value: number` - The current value for the handle
  - `active: boolean` - Denotes if the handle is currently being dragged.
  - `getHandleProps(userProps): func` - A function that take optional props and returns the combined necessary props for the handle component.
- `activeHandleIndex: oneOfType([null, number])` - The zero-based index of the handle that is currently being dragged, or `null` if no handle is being dragged.

## Interpolation

By default, `react-ranger` uses linear interpolation between data points, but allows you to easily customize it to use your own interpolation functions by passing an object that implements the following interface:

```
const interpolator = {
  // Takes the value & range and returns a percentage [0, 100] where the value sits from left to right
  getPercentageForValue: (val: number, min: number, max: number): number

  // Takes the clientX (offset from the left edge of the ranger) along with the dimensions
  // and range settings and transforms a pixel coordinate back into a value
  getValueForClientX: (clientX: number, trackDims: object, min: number, max: number): number
}
```

Here is an exmaple of building and using a logarithmic interpolator!

```javascript
import { useRanger } from 'react-ranger'

const logInterpolator = {
  getPercentageForValue: (val, min, max) => {
    const minSign = Math.sign(min)
    const maxSign = Math.sign(max)

    if (minSign !== maxSign) {
      throw new Error(
        'Error: logarithmic interpolation does not support ranges that cross 0.'
      )
    }

    let percent =
      (100 / (Math.log10(Math.abs(max)) - Math.log10(Math.abs(min)))) *
      (Math.log10(Math.abs(val)) - Math.log10(Math.abs(min)))

    if (minSign < 0) {
      // negative range, means we need to invert our percent because of the Math.abs above
      return 100 - percent
    }

    return percent
  },
  getValueForClientX: (clientX, trackDims, min, max) => {
    const { left, width } = trackDims
    let value = clientX - left
    value *= Math.log10(max) - Math.log10(min)
    value /= width
    value = Math.pow(10, Math.log10(min) + value)
    return value
  },
}

useRanger({
  interpolator: logInterpolator,
})
```

# Contributors ✨

Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):

<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<table>
  <tr>
    <td align="center"><a href="https://tannerlinsley.com"><img src="https://avatars0.githubusercontent.com/u/5580297?v=4" width="100px;" alt=""/><br /><sub><b>Tanner Linsley</b></sub></a><br /><a href="https://github.com/tannerlinsley/react-ranger/commits?author=tannerlinsley" title="Code">💻</a> <a href="#ideas-tannerlinsley" title="Ideas, Planning, & Feedback">🤔</a> <a href="#example-tannerlinsley" title="Examples">💡</a> <a href="#maintenance-tannerlinsley" title="Maintenance">🚧</a> <a href="https://github.com/tannerlinsley/react-ranger/pulls?q=is%3Apr+reviewed-by%3Atannerlinsley" title="Reviewed Pull Requests">👀</a></td>
    <td align="center"><a href="http://everttimberg.io"><img src="https://avatars3.githubusercontent.com/u/6757853?v=4" width="100px;" alt=""/><br /><sub><b>Evert Timberg</b></sub></a><br /><a href="https://github.com/tannerlinsley/react-ranger/commits?author=etimberg" title="Code">💻</a> <a href="#ideas-etimberg" title="Ideas, Planning, & Feedback">🤔</a></td>
  </tr>
</table>

<!-- markdownlint-enable -->
<!-- prettier-ignore-end -->

<!-- ALL-CONTRIBUTORS-LIST:END -->

This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!

<!-- Force -->

---
_Source: https://npm.io/package/react-ranger · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
