Tanstack Ranger

tanstack-skills/tanstack-skills/plugins/tanstack-ranger/skills/tanstack-ranger

作者 tanstack-skills6f5521ecbdfb無授權條款35 個星標收錄於 2026年10月8日更新於 2026年10月8日儲存庫8 個月前更新

Headless utilities for building range and multi-range sliders in TS/JS, React, Vue, Solid, Svelte & Angular.

AI 產生的概覽

TanStack Ranger 參考指南,說明如何在 TS/JS 框架中打造無障礙範圍與多範圍滑桿的 headless 工具。

功能
說明 TanStack Ranger 這套 headless 滑桿函式庫,涵蓋安裝、useRanger hook、必填與選用選項,以及 ranger 實例與 handle API。提供單值、範圍與多滑塊、自訂步進、刻度標記與對數刻度的程式碼範例。也涵蓋無障礙屬性、受控用法、樣式建議、框架轉接器、最佳實務與常見陷阱。
適用情境
在 React、Vue、Solid、Svelte 或 Angular 中以 TanStack Ranger 實作範圍或多範圍滑桿元件時使用。適合需要 headless 滑桿邏輯、無障礙滑塊握把、自訂步進或刻度,或非線性數值刻度的情況。
執行需求
僅為說明文件,未附帶指令碼。依範例操作需要 Node.js 與 npm 來安裝 @tanstack/react-ranger 或對應框架的套件,並需要支援的框架,例如 React、Vue、Solid、Svelte 或 Angular。

Overview

TanStack Ranger provides headless utilities for building fully accessible range and multi-range slider components. It handles all the complex logic for single value, range, and multi-thumb sliders while giving you complete control over styling and markup.

Package: @tanstack/react-ranger Core: @tanstack/ranger-core (framework-agnostic) Status: Stable

Installation

bash
npm install @tanstack/react-ranger

Core Pattern

tsx
import { useRanger } from '@tanstack/react-ranger'
function RangeSlider() {  const [values, setValues] = useState([25, 75])
  const rangerInstance = useRanger({    getRangerElement: () => rangerRef.current,    values,    min: 0,    max: 100,    stepSize: 1,    onChange: (instance) => setValues(instance.sortedValues),  })
  const rangerRef = useRef<HTMLDivElement>(null)
  return (    <div      ref={rangerRef}      style={{        position: 'relative',        height: '8px',        background: '#ddd',        borderRadius: '4px',        width: '100%',      }}    >      {/* Track segments */}      {rangerInstance.getSteps().map(({ left, width }, i) => (        <div          key={i}          style={{            position: 'absolute',            left: `${left}%`,            width: `${width}%`,            height: '100%',            background: i === 1 ? '#3b82f6' : '#ddd',            borderRadius: '4px',          }}        />      ))}
      {/* Thumbs */}      {rangerInstance.handles.map((handle, i) => (        <button          key={i}          {...handle.getHandleProps()}          style={{            position: 'absolute',            left: `${handle.getPercentage()}%`,            transform: 'translateX(-50%)',            width: '20px',            height: '20px',            borderRadius: '50%',            background: '#3b82f6',            border: '2px solid white',            cursor: 'grab',          }}        />      ))}    </div>  )}

Ranger Options

Required

OptionTypeDescription
getRangerElement() => Element | nullReturns the slider track element
valuesnumber[]Current thumb values
minnumberMinimum value
maxnumberMaximum value
onChange(instance) => voidCalled when values change

Optional

OptionTypeDefaultDescription
stepSizenumber1Step increment between values
stepsnumber[]-Custom step positions (overrides stepSize)
tickSizenumber-Size of tick marks
ticksnumber[]-Custom tick positions
interpolatorInterpolatorlinearValue interpolation function
onDrag(instance) => void-Called during drag operations

Ranger Instance API

typescript
// Get sorted values (always ascending order)rangerInstance.sortedValues: number[]
// Get handles for rendering thumbsrangerInstance.handles: Handle[]
// Get track segments between handlesrangerInstance.getSteps(): { left: number; width: number }[]
// Get tick marksrangerInstance.getTicks(): { value: number; percentage: number }[]
// Programmatically set valuesrangerInstance.setValues(newValues: number[])

Handle API

typescript
interface Handle {  // Get percentage position on track (0-100)  getPercentage(): number
  // Get the current value  getValue(): number
  // Get props to spread on handle element  getHandleProps(): {    role: 'slider'    tabIndex: number    'aria-valuemin': number    'aria-valuemax': number    'aria-valuenow': number    onKeyDown: (e: KeyboardEvent) => void    onMouseDown: (e: MouseEvent) => void    onTouchStart: (e: TouchEvent) => void  }}

Single Value Slider

tsx
function SingleSlider() {  const [values, setValues] = useState([50])
  const rangerInstance = useRanger({    getRangerElement: () => rangerRef.current,    values,    min: 0,    max: 100,    stepSize: 1,    onChange: (instance) => setValues(instance.sortedValues),  })
  const rangerRef = useRef<HTMLDivElement>(null)
  return (    <div ref={rangerRef} className="slider-track">      {rangerInstance.handles.map((handle, i) => (        <button key={i} {...handle.getHandleProps()} className="slider-thumb">          {handle.getValue()}        </button>      ))}    </div>  )}

Multi-Range Slider

tsx
function MultiRangeSlider() {  const [values, setValues] = useState([10, 40, 60, 90])
  const rangerInstance = useRanger({    getRangerElement: () => rangerRef.current,    values,    min: 0,    max: 100,    stepSize: 5,    onChange: (instance) => setValues(instance.sortedValues),  })
  const rangerRef = useRef<HTMLDivElement>(null)
  return (    <div ref={rangerRef} className="slider-track">      {rangerInstance.getSteps().map(({ left, width }, i) => (        <div          key={i}          className={`segment ${i % 2 === 1 ? 'active' : ''}`}          style={{ left: `${left}%`, width: `${width}%` }}        />      ))}      {rangerInstance.handles.map((handle, i) => (        <button key={i} {...handle.getHandleProps()} className="slider-thumb" />      ))}    </div>  )}

Custom Steps

tsx
const rangerInstance = useRanger({  getRangerElement: () => rangerRef.current,  values,  min: 0,  max: 100,  steps: [0, 10, 25, 50, 75, 100], // Only these values allowed  onChange: (instance) => setValues(instance.sortedValues),})

Tick Marks

tsx
function SliderWithTicks() {  const rangerInstance = useRanger({    getRangerElement: () => rangerRef.current,    values,    min: 0,    max: 100,    stepSize: 10,    ticks: [0, 25, 50, 75, 100],    onChange: (instance) => setValues(instance.sortedValues),  })
  return (    <div>      <div ref={rangerRef} className="slider-track">        {/* Handles */}      </div>      <div className="tick-container">        {rangerInstance.getTicks().map((tick, i) => (          <div            key={i}            style={{ left: `${tick.percentage}%` }}            className="tick"          >            <span className="tick-label">{tick.value}</span>          </div>        ))}      </div>    </div>  )}

Logarithmic Scale

tsx
import { logarithmicInterpolator } from '@tanstack/react-ranger'
const rangerInstance = useRanger({  getRangerElement: () => rangerRef.current,  values,  min: 1,  max: 1000,  interpolator: logarithmicInterpolator,  onChange: (instance) => setValues(instance.sortedValues),})

Accessibility

TanStack Ranger provides built-in accessibility:

  • role="slider" on handles
  • aria-valuemin, aria-valuemax, aria-valuenow attributes
  • Keyboard navigation (Arrow keys, Home, End, Page Up/Down)
  • Focus management
tsx
// Add aria-label for screen readers<button  {...handle.getHandleProps()}  aria-label={`Value: ${handle.getValue()}`}/>

Controlled vs Uncontrolled

tsx
// Controlled (recommended)const [values, setValues] = useState([50])const ranger = useRanger({  values,  onChange: (instance) => setValues(instance.sortedValues),  // ...})
// With validationconst handleChange = (instance) => {  const [min, max] = instance.sortedValues  // Ensure minimum gap of 10  if (max - min >= 10) {    setValues(instance.sortedValues)  }}

Styling Tips

css
/* Track */.slider-track {  position: relative;  height: 8px;  background: #e5e7eb;  border-radius: 4px;  width: 100%;}
/* Active segment */.segment.active {  background: #3b82f6;}
/* Thumb */.slider-thumb {  position: absolute;  transform: translateX(-50%);  width: 20px;  height: 20px;  border-radius: 50%;  background: #3b82f6;  border: 2px solid white;  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);  cursor: grab;}
.slider-thumb:active {  cursor: grabbing;}
.slider-thumb:focus {  outline: none;  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.3);}

Framework Adapters

FrameworkPackageStatus
React@tanstack/react-rangerStable
Vue@tanstack/vue-rangerStable
Solid@tanstack/solid-rangerStable
Svelte@tanstack/svelte-rangerStable
Angular@tanstack/angular-rangerStable
Core@tanstack/ranger-coreStable

Best Practices

  1. Always use sortedValues from onChange - handles may cross during drag
  2. Memoize getRangerElement callback to prevent unnecessary re-renders
  3. Use semantic HTML - render handles as <button> elements for accessibility
  4. Add aria-label to describe each handle's purpose
  5. Use CSS transforms (translateX) for positioning instead of left for better performance
  6. Validate in onChange to enforce constraints (min gap, max range, etc.)
  7. Use onDrag for real-time feedback during drag operations
  8. Consider touch targets - make handles at least 44x44px on mobile

Common Pitfalls

  • Forgetting position: relative on the track container
  • Using values instead of sortedValues (handles can swap positions)
  • Not providing getRangerElement as a callback
  • Setting thumb position with left instead of transform: translateX()
  • Forgetting to handle keyboard navigation (built-in via getHandleProps)
  • Not accounting for thumb width when calculating positions

來源與署名

來源:tanstack-skills/tanstack-skills位於plugins/tanstack-ranger/skills/tanstack-ranger提交6f5521e

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架