Blog>
Snippets

Initializing TanStack Ranger in a React Component

Show how to set up TanStack Ranger within a React function component, including the basic configuration and the use of hooks for state management.
import { useRanger } from 'tanstack-ranger';
First, import the useRanger hook from the tanstack-ranger package.
function SliderComponent() {
  // Setting up the state for the slider value
  const [values, setValues] = React.useState([25]);
  // Initializing TanStack Ranger
  const { getTrackProps, handles } = useRanger({
    values,
    onChange: setValues,
    onDrag: setValues,
    min: 0,
    max: 100,
    stepSize: 1
  });

  return (
    <div {...getTrackProps()}>
      {handles.map(({ getHandleProps }) => (
        <button {...getHandleProps()} />
      ))}
    </div>
  );
}
Here, we set up a simple slider component using TanStack Ranger. We manage the slider's state with React's useState hook, initializing the slider with a default value. The useRanger hook is then utilized to provide the necessary functionality for the slider, such as tracking changes and drag events. The min, max, and stepSize define the slider's range and increments. Within the JSX, getTrackProps is spread onto the main div element to handle track events, and each handle's properties are spread onto button elements.