Blog>
Snippets

Initializing TanStack Ranger in a React Project

Demonstrate how to set up TanStack Ranger within a React application, including importing necessary modules and initializing a basic Ranger component.
import { useRanger } from 'tanstack-ranger-react';
Imports the useRanger hook from 'tanstack-ranger-react' package.
function RangeSlider() {
  const [values, setValues] = React.useState([10, 90]);
  const { getTrackProps, segments } = useRanger({
    values,
    onChange: setValues,
    min: 0,
    max: 100,
    stepSize: 5
  });
  return (
    <div {...getTrackProps({
      style: {
        height: '4px',
        background: 'grey',
        position: 'relative',
        width: '100%'
      }
    })}>
      {segments.map((segment, i) => (
        <div key={i} {...segment.getHandleProps({
          style: {
            position: 'absolute',
            marginLeft: '-5px',
            marginTop: '-3px',
            zIndex: 1,
            width: '10px',
            height: '10px',
            borderRadius: '5px',
            backgroundColor: 'blue'
          }
        })} />
      ))}
    </div>
  );
}
Defines a RangeSlider component that uses the useRanger hook to create a range slider. 'values' holds the current positions of the range thumbs, which is initially set to 10 and 90. 'setValues' is the method to update these values. 'getTrackProps' and 'segments' provide the necessary props to render the track and the thumbs, respectively. The track is styled with basic CSS for demonstration.