Blog>
Snippets

Setting Up TanStack Ranger in a React Project

Show how to install TanStack Ranger via npm and setup a basic Ranger instance in a React application.
npm install @tanstack/react-ranger
This command installs the TanStack Ranger package for React via npm. It's the first step to set it up in your project.
import { useState } from 'react';
import { useRanger } from '@tanstack/react-ranger';
Imports the useState hook from React and the useRanger hook from TanStack Ranger at the beginning of your component file.
const [values, setValues] = useState([10]);
const { getTrackProps, handles } = useRanger({
  values,
  onChange: setValues,
  min: 0,
  max: 100,
  stepSize: 5
});
Sets up a basic Ranger instance. A local state 'values' is used to store the current value, initially set to 10. The useRanger hook is initialized with this value, and an `onChange` function to update it. Also, it specifies the minimum, maximum values and the step size for the ranger.
return (
  <div {...getTrackProps({
    style: {
      height: '4px',
      background: 'grey',
      boxShadow: 'inset 0 1px 2px rgba(0,0,0,0.2)',
      borderRadius: '2px',
    }
  })}>
    {handles.map(({ getHandleProps }) => (
      <button
        {...getHandleProps()}
        style={{
          width: '12px',
          height: '12px',
          borderRadius: '100%',
          background: 'blue'
        }}
      />
    ))}
  </div>
);
Returns the Ranger component. It utilizes the `getTrackProps` function to provide the track (slider path) properties and maps over the `handles` array (from `useRanger` hook) to render the slider handles. Styling is applied directly for simplicity.