Range slider

A slider with two handles for a lowest and a highest value, such as a budget, with the range written out above it. It is two real range inputs over one track, so the keyboard works as usual.

Budget$2,000 to $8,000

Options

Size
Colour

Code

import { useId, useState } from "react";
import "./range-slider.css";

/* A slider with two handles. value is [lowest, highest].

   <RangeSlider label="Budget" min={0} max={10000} step={500} prefix="$" value={budget} onChange={setBudget} /> */
export function RangeSlider({ label, min = 0, max = 100, step = 1, prefix = "", value, onChange }) {
  const id = useId();
  const [low, high] = value;
  const share = (amount) => (amount - min) / (max - min);
  const text = (amount) => prefix + amount.toLocaleString("en-US");

  /* The handles stop one step short of each other. */
  const setLow = (amount) => onChange([Math.min(amount, high - step), high]);
  const setHigh = (amount) => onChange([low, Math.max(amount, low + step)]);

  return (
    <div
      className="dh-range"
      role="group"
      aria-labelledby={id}
      style={{ "--lo": share(low), "--hi": share(high) }}
    >
      <p>
        <span id={id}>{label}</span>
        <output>
          {text(low)} to {text(high)}
        </output>
      </p>
      <div>
        <input
          type="range"
          min={min}
          max={max}
          step={step}
          value={low}
          aria-label={"Lowest " + label.toLowerCase()}
          aria-valuetext={text(low)}
          onChange={(event) => setLow(Number(event.target.value))}
        />
        <input
          type="range"
          min={min}
          max={max}
          step={step}
          value={high}
          aria-label={"Highest " + label.toLowerCase()}
          aria-valuetext={text(high)}
          onChange={(event) => setHigh(Number(event.target.value))}
        />
      </div>
      <p aria-hidden="true">
        <small>{text(min)}</small>
        <small>{text((min + max) / 2)}</small>
        <small>{text(max)}</small>
      </p>
    </div>
  );
}

export function Example() {
  const [budget, setBudget] = useState([2000, 8000]);
  return <RangeSlider label="Budget" min={0} max={10000} step={500} prefix="$" value={budget} onChange={setBudget} />;
}

Budget$2,000 to $8,000