react-range

Range input with a slider. Accessible. Bring your own styles and markup.

README

react-range

npm version npm downloads Build Status size

Labeled Range
Edit react-range


Installation


  1. ```
  2. yarn add react-range
  3. ```

Usage


  1. ``` js
  2. import * as React from 'react';
  3. import { Range } from 'react-range';

  4. class SuperSimple extends React.Component {
  5.   state = { values: [50] };
  6.   render() {
  7.     return (
  8.       <Range
  9.         step={0.1}
  10.         min={0}
  11.         max={100}
  12.         values={this.state.values}
  13.         onChange={(values) => this.setState({ values })}
  14.         renderTrack={({ props, children }) => (
  15.           <div
  16.             {...props}
  17.             style={{
  18.               ...props.style,
  19.               height: '6px',
  20.               width: '100%',
  21.               backgroundColor: '#ccc'
  22.             }}
  23.           >
  24.             {children}
  25.           </div>
  26.         )}
  27.         renderThumb={({ props }) => (
  28.           <div
  29.             {...props}
  30.             style={{
  31.               ...props.style,
  32.               height: '42px',
  33.               width: '42px',
  34.               backgroundColor: '#999'
  35.             }}
  36.           />
  37.         )}
  38.       />
  39.     );
  40.   }
  41. }
  42. ```

Features


- Range input supporting vertical and horizontal sliding
- Unopinionated styling, great for CSS in JS too
- No wrapping divs or additional markup, bring your own!
- Accessible, made for keyboards and screen readers
- Touchable, works on mobile devices
- Can handle negative and decimal values
- Stateless and controlled single component
- Typescript and Flow type definitions
- No dependencies, less than 5kB (gzipped)
- Coverage by e2e puppeteer tests
- RTL support

Keyboard support


- tab and shift+tab to focus thumbs
- arrow up or arrow right or k to increase the thumb value by one step
- arrow down or arrow left or j to decrease the thumb value by one step
- page up to increase the thumb value by ten steps
- page down to decrease the thumb value by ten steps

## `` props

renderTrack


  1. ```ts
  2. renderTrack: (params: {
  3.   props: {
  4.     style: React.CSSProperties;
  5.     ref: React.RefObject<any>;
  6.     onMouseDown: (e: React.MouseEvent) => void;
  7.     onTouchStart: (e: React.TouchEvent) => void;
  8.   };
  9.   children: React.ReactNode;
  10.   isDragged: boolean;
  11.   disabled: boolean;
  12. }) => React.ReactNode;
  13. ```

renderTrack prop to define your track (root) element. Your function gets four parameters and should return a React component:

- props - this needs to be spread over the root track element, it connects mouse and touch events, adds a ref and some necessary styling
- children - the rendered thumbs, thumb structure should be specified in a different prop - renderThumb
- isDragged - true if any thumb is being dragged
- `disabled` - `true` if `` is set

The track can be a single narrow div as in the Super simple example; however, it might be better to use at least two nesteddivs where the outer div is much thicker and has a transparent background and the inner div is narrow, has visible background and is centered. props should be then spread over the outer bigger div. Why to do this? It's nice to keep the onMouseDown and onTouchStart targets bigger since the thumb can be moved also by clicking on the track (in a single thumb scenario).

renderThumb


  1. ```ts
  2. renderThumb: (params: {
  3.   props: {
  4.     key: number;
  5.     style: React.CSSProperties;
  6.     tabIndex?: number;
  7.     'aria-valuemax': number;
  8.     'aria-valuemin': number;
  9.     'aria-valuenow': number;
  10.     draggable: boolean;
  11.     role: string;
  12.     onKeyDown: (e: React.KeyboardEvent) => void;
  13.     onKeyUp: (e: React.KeyboardEvent) => void;
  14.   };
  15.   value: number;
  16.   index: number;
  17.   isDragged: boolean;
  18. }) => React.ReactNode;
  19. ```

renderThumb prop to define your thumb. Your function gets four parameters and should return a React component:

- props - it has multiple props that you need to spread over your thumb element
- value - a number, relative value based on min, max, step and the thumb's position
- index - the thumb index (order)
- isDragged - true if the thumb is dragged, great for styling purposes

renderMark (optional)


  1. ```ts
  2. renderMark?: (params: {
  3.   props: {
  4.     key: string;
  5.     style: React.CSSProperties;
  6.     ref: React.RefObject<any>;
  7.   };
  8.   index: number;
  9. }) => React.ReactNode;
  10. ```

renderMark is an optional prop so you can render an element at each step. See this example.Your function gets 2 parameters and should return a React component:

- props - this needs to be spread over the root track element, it adds a ref, key and some necessary styling
- index - index of the mark, might be useful if you want to use different styles for even/odd marks

You can use any dimensions for your marks and react-range will automatically position them at the correct place.

values


  1. ```ts
  2. values: number[];
  3. ```

An array of numbers. It controls the position of thumbs on the track. values.length equals to the number of rendered thumbs.

onChange


  1. ```ts
  2. onChange: (values: number[]) => void;
  3. ```

Called when a thumb is moved, provides new values.

onFinalChange


  1. ```ts
  2. onFinalChange: (values: number[]) => void;
  3. ```

Called when a change is finished (mouse/touch up, or keyup), provides current values. Use this event when you have to make for example ajax request with new values.

min (optional)


  1. ```ts
  2. min: number;
  3. ```

The range start. Can be decimal or negative. Default is 0.

max (optional)


  1. ```ts
  2. max: number;
  3. ```

The range end. Can be decimal or negative. Default is 100.

step (optional)


  1. ```ts
  2. step: number;
  3. ```

The minimal distance between two values. Can be decimal. Default is 1.

allowOverlap (optional)


  1. ```ts
  2. allowOverlap: boolean;
  3. ```

When there are multiple thumbs on a single track, should they be allowed to overlap? Default is false.

draggableTrack (optional)


  1. ```ts
  2. draggableTrack: boolean;
  3. ```

When there are multiple thumbs on a single track, should it be possible to drag all thumbs at once? Default is false.

direction (optional)


  1. ```ts
  2. direction: Direction;

  3. enum Direction {
  4.   Right = 'to right',
  5.   Left = 'to left',
  6.   Down = 'to bottom',
  7.   Up = 'to top'
  8. }
  9. ```

It sets the orientation (vertical vs horizontal) and the direction in which the value increases. You can get this enum by:

  1. ``` js
  2. import { Direction } from 'react-range';
  3. ```

Default value is Direction.Right.

disabled (optional)


  1. ```ts
  2. disabled: boolean;
  3. ```

If true, it ignores all touch and mouse events and makes the component not focusable. Default is false.

rtl (optional)


  1. ```ts
  2. rtl: boolean;
  3. ```

If true, the slider will be optimized for RTL layouts. Default is false.

getTrackBackground


There is an additional helper function being exported from react-range. Your track is most likely a div with some background. What if you want to achieve a nice "progress bar" effect where the part before the thumb has different color than the part after? What if you want to have the same thing even with multiple thumbs (aka differently colored segments)? You don't need to glue together multiple divs in order to do that! You can use a single div and set background: linear-gradient(...). getTrackBackground function builds this verbose linear-gradient(...) for you!

  1. ```ts
  2. getTrackBackground: (params: {
  3.   min: number;
  4.   max: number;
  5.   values: number[];
  6.   colors: string[];
  7.   direction?: Direction;
  8.   rtl?: boolean;
  9. }) => string;
  10. ```

`min`, `max`, `values` and `direction` should be same as for the `` component. `colors` is a list of colors. This needs to be true:

  1. ``` js
  2. values.length + 1 === colors.length;
  3. ```

That's because one thumb (one value) splits the track into two segments, so you need two colors.

Motivation


There is a native input solution:

  1. ``` html
  2. <input type="range" />
  3. ```

However, it has some serious shortcomings:

- vertical-oriented slider is not supported in all browsers
- supports only a single direction
- very limited styling options
- no support for multiple thumbs

There are also many React based solutions but most of them are too bloated, don't support styling through CSS in JS or have lacking performance.

react-range has two main goals:

- Small footprint - less then 4kB gzipped, single component.
- Bring your own styles and HTML markup - react-range is a more low-level approach than other libraries. It doesn't come with any styling (except some positioning) or markup. It's up to the user to specify both! Think about react-range as a foundation for other styled input ranges.

End to end testing


This library is tightly coupled to many DOM APIs. It would be very hard to ensure 100% test coverage just with unit tests that would not involve a lot of mocking. Or we could re-architect the library to better abstract all DOM interfaces but that would mean more code and bigger footprint.

Instead of that, react-range adds thorough end to end tests powered by puppeteer.

All tests are automatically ran in Travis CI with headless chromium. This way, the public API is well tested, including pixel-perfect positioning. Also, the tests are pretty fast, reliable and very descriptive.

Do you want to run them in the dev mode (slows down operations, opens the browser)?

  1. ``` sh
  2. yarn ladle serve #start the ladle server
  3. yarn test:e2e:dev #run the e2e tests
  4. ```

CI mode (ladle started on the background, quick, headless)

  1. ``` sh
  2. yarn test:e2e
  3. ```

Browser support


- Chrome (latest, mac, windows, iOS, Android)
- Firefox (latest, mac, windows)
- Safari (latest, mac, iOS)
- Edge (latest, windows)

Contributing


This is how you can spin up the dev environment:

  1. ```
  2. git clone https://github.com/tajo/react-range
  3. cd react-range
  4. yarn
  5. yarn ladle serve
  6. ```

Shoutouts 🙏


Big big shoutout to Tom MacWright for donating the react-range npm handle! ❤️

BrowserStack Logo

Big thanks to BrowserStack for letting the maintainers use their service to debug browser issues.

And Netlify for free hosting.

Author


Vojtech Miksu 2019, miksu.cz, @vmiksu