UIPackage React Native
Search

Range Slider

Dual-thumb bounded range slider with stepped values, controlled refusal, and adjustable thumbs.

Install

First install? Set up the registry in your app.

npx --yes --package=https://native.uipkge.dev/cli/uipkge-native-0.1.1.tgz uipkge-native add range-slider

Source files

Expand a file to read the source the installer copies into your app.

components/ui/range-slider/RangeSlider.tsx
import * as React from 'react'
import { I18nManager, View, type LayoutChangeEvent, type ViewProps } from 'react-native'
import { Gesture, GestureDetector, GestureHandlerRootView } from 'react-native-gesture-handler'
import { cn } from '@/lib/utils'

export type RangeValue = [number, number]
type Thumb = 0 | 1

export interface RangeSliderProps extends Omit<ViewProps, 'children'> {
  min?: number
  max?: number
  /** Positive step size. Values snap to `min + n * step`; `max` stays reachable. Non-positive means continuous. */
  step?: number
  value?: RangeValue
  defaultValue?: RangeValue
  disabled?: boolean
  /** Lower and upper thumb names for assistive technology. */
  thumbLabels?: [string, string]
  /** Called with each new pair while dragging or adjusting. A controlled owner may refuse it. */
  onValueChange?: (value: RangeValue) => void
  /** Called once when a drag or accessibility adjustment ends with the last requested pair. */
  onSlidingComplete?: (value: RangeValue) => void
  className?: string
}

/** Touch target edge; the track is inset by half of it so both thumbs fit at the ends. */
const HIT = 48
const HALF = HIT / 2

function decimals(value: number) {
  const text = String(value)
  if (text.includes('e-')) return Number(text.split('e-')[1])
  return text.includes('.') ? text.split('.')[1].length : 0
}

interface Scale {
  min: number
  max: number
  step: number
  places: number
}
function scaleOf(min: number, max: number, step: number): Scale {
  const lo = Number.isFinite(min) ? min : 0
  const hi = Number.isFinite(max) && max > lo ? max : lo
  const size = Number.isFinite(step) && step > 0 ? step : 0
  const places = Math.min(10, Math.max(decimals(size), decimals(lo), decimals(hi)))
  return { min: lo, max: hi, step: size, places }
}
function snap(value: number, scale: Scale) {
  if (!Number.isFinite(value) || value <= scale.min) return scale.min
  // Endpoints are returned exactly: rounding an off-grid max (10.5 -> 11) would escape the bounds.
  if (value >= scale.max) return scale.max
  if (!scale.step) return value
  const round = (next: number) => Number(next.toFixed(scale.places))
  // The last grid point may fall short of an off-grid max; max itself is a valid stop when nearer.
  const lastGrid = round(scale.min + Math.floor((scale.max - scale.min) / scale.step + 1e-9) * scale.step)
  const stepped = Math.min(lastGrid, round(scale.min + Math.round((value - scale.min) / scale.step) * scale.step))
  if (value - stepped > scale.max - value) return scale.max
  return Math.min(scale.max, Math.max(scale.min, stepped))
}
function normalize(pair: RangeValue | undefined, scale: Scale): RangeValue {
  const lower = snap(pair?.[0] ?? scale.min, scale)
  const upper = snap(pair?.[1] ?? scale.max, scale)
  return lower <= upper ? [lower, upper] : [upper, lower]
}
function same(a: RangeValue, b: RangeValue) {
  return a[0] === b[0] && a[1] === b[1]
}

/**
 * iOS Fabric only accepts integers in accessibilityValue min/max/now and crashes on fractions,
 * so decimal ranges are announced through text alone.
 */
function accessibleValue(min: number, max: number, now: number) {
  const text = String(now)
  return [min, max, now].every(Number.isInteger) ? { min, max, now, text } : { text }
}

interface Drag {
  thumb: Thumb | null
  offset: number
  requested: RangeValue | null
  startX: number
}

export const RangeSlider = React.forwardRef<React.ComponentRef<typeof View>, RangeSliderProps>(
  (
    {
      min = 0,
      max = 100,
      step = 1,
      value,
      defaultValue,
      disabled = false,
      thumbLabels = ['Minimum', 'Maximum'],
      onValueChange,
      onSlidingComplete,
      className,
      ...props
    },
    ref,
  ) => {
    const scale = scaleOf(min, max, step)
    const [internal, setInternal] = React.useState<RangeValue | undefined>(defaultValue)
    const [width, setWidth] = React.useState(0)
    const current = normalize(value ?? internal, scale)
    const travel = Math.max(0, width - HIT)
    const span = scale.max - scale.min
    const adjustable = !disabled && span > 0
    const interactive = adjustable && travel > 0
    const rtl = I18nManager.isRTL

    // Gesture callbacks run on the JS thread and may outlive a render; read live values from refs.
    const live = React.useRef({
      current,
      scale,
      width,
      travel,
      rtl,
      interactive,
      value,
      onValueChange,
      onSlidingComplete,
    })
    live.current = { current, scale, width, travel, rtl, interactive, value, onValueChange, onSlidingComplete }
    const drag = React.useRef<Drag>({ thumb: null, offset: 0, requested: null, startX: 0 })

    // Bounds, step, or availability changing under a finger invalidate the drag geometry: drop it.
    React.useEffect(() => {
      drag.current = { thumb: null, offset: 0, requested: null, startX: 0 }
    }, [scale.min, scale.max, scale.step, interactive, travel])

    const position = (next: number) => HALF + (span > 0 ? ((next - scale.min) / span) * travel : 0)

    function request(next: RangeValue) {
      const state = live.current
      if (same(next, state.current)) return false
      if (state.value === undefined) setInternal(next)
      state.onValueChange?.(next)
      return true
    }
    function move(thumb: Thumb, target: number): RangeValue {
      const [lower, upper] = live.current.current
      const snapped = snap(target, live.current.scale)
      // Thumbs never cross: each one stops at the other.
      return thumb === 0 ? [Math.min(snapped, upper), upper] : [lower, Math.max(snapped, lower)]
    }
    function valueAt(logicalX: number) {
      const state = live.current
      const ratio = state.travel ? (logicalX - HALF) / state.travel : 0
      return state.scale.min + ratio * (state.scale.max - state.scale.min)
    }
    const logical = (x: number) => (live.current.rtl ? live.current.width - x : x)

    const pan = Gesture.Pan()
      .runOnJS(true)
      .enabled(interactive)
      // Horizontal intent only; vertical movement fails fast so a parent ScrollView keeps scrolling.
      .activeOffsetX([-10, 10])
      .failOffsetY([-10, 10])
      .onBegin((event) => {
        if (!live.current.interactive) return
        const x = logical(event.x)
        const [lower, upper] = live.current.current
        const lowerX = position(lower)
        const upperX = position(upper)
        // Overlapping thumbs are resolved by the first movement direction in onStart.
        const thumb: Thumb | null = lowerX === upperX ? null : Math.abs(x - lowerX) <= Math.abs(x - upperX) ? 0 : 1
        const thumbX = thumb === 1 ? upperX : lowerX
        drag.current = {
          thumb,
          // Grabbing a thumb keeps its grip point; touching bare track moves the nearest thumb to the finger.
          offset: Math.abs(x - thumbX) <= HALF ? x - thumbX : 0,
          requested: null,
          startX: x,
        }
      })
      .onStart((event) => {
        const state = drag.current
        if (state.thumb !== null) return
        const forward = logical(event.x) >= state.startX
        const [lower, upper] = live.current.current
        // Stacked at an end, only one direction can move: pick the thumb that can.
        if (upper >= live.current.scale.max) state.thumb = 0
        else if (lower <= live.current.scale.min) state.thumb = 1
        else state.thumb = forward ? 1 : 0
      })
      .onUpdate((event) => {
        const state = drag.current
        if (state.thumb === null || !live.current.interactive) return
        const next = move(state.thumb, valueAt(logical(event.x) - state.offset))
        if (state.requested && same(next, state.requested)) return
        state.requested = next
        request(next)
      })
      .onEnd(() => {
        const state = drag.current
        if (state.thumb !== null && state.requested) live.current.onSlidingComplete?.(state.requested)
      })
      .onFinalize(() => {
        drag.current = { thumb: null, offset: 0, requested: null, startX: 0 }
      })

    function adjust(thumb: Thumb, direction: 1 | -1) {
      if (!adjustable) return
      const delta = scale.step || span / 100
      const next = move(thumb, current[thumb] + direction * delta)
      if (request(next)) onSlidingComplete?.(next)
    }

    const fillStart = position(current[0])
    const fillEnd = position(current[1])
    return (
      <GestureHandlerRootView style={{ flexGrow: 0, flexShrink: 0 }}>
        <GestureDetector gesture={pan}>
          <View
            {...props}
            ref={ref}
            className={cn('h-[48px] w-full justify-center', disabled && 'opacity-50', className)}
            onLayout={(event: LayoutChangeEvent) => {
              setWidth(Math.max(0, event.nativeEvent.layout.width))
              props.onLayout?.(event)
            }}
          >
            <View
              pointerEvents="none"
              className="absolute h-[4px] rounded-full bg-input"
              style={{ start: HALF, end: HALF }}
            />
            <View
              pointerEvents="none"
              className="absolute h-[4px] rounded-full bg-primary"
              style={{ start: fillStart, width: Math.max(0, fillEnd - fillStart) }}
            />
            {([0, 1] as const).map((thumb) => (
              <View
                key={thumb}
                accessible
                accessibilityRole="adjustable"
                accessibilityLabel={thumbLabels[thumb]}
                accessibilityState={{ disabled: !adjustable }}
                accessibilityValue={accessibleValue(
                  thumb === 0 ? scale.min : current[0],
                  thumb === 0 ? current[1] : scale.max,
                  current[thumb],
                )}
                accessibilityActions={[{ name: 'increment' }, { name: 'decrement' }]}
                onAccessibilityAction={(event) => {
                  if (event.nativeEvent.actionName === 'increment') adjust(thumb, 1)
                  else if (event.nativeEvent.actionName === 'decrement') adjust(thumb, -1)
                }}
                className="absolute top-0 size-[48px] items-center justify-center"
                style={{ start: position(current[thumb]) - HALF }}
              >
                <View
                  pointerEvents="none"
                  className="size-[24px] rounded-full border-2 border-background bg-primary shadow-sm"
                />
              </View>
            ))}
          </View>
        </GestureDetector>
      </GestureHandlerRootView>
    )
  },
)
RangeSlider.displayName = 'RangeSlider'
components/ui/range-slider/index.ts
export { RangeSlider, type RangeSliderProps, type RangeValue } from './RangeSlider'

Dependencies

Registry items

npm packages

  • react-native-gesture-handler
Browse controls and interactions