日本語

How to Build a Two-Handle Range Slider in React

​​React​Accessibility,CSS,Forms,Playwright,TypeScript

A two-handle range slider can be built without a library by stacking two <input type="range"> elements in the same place. In CSS, the input boxes are set to not receive clicks, so only the thumbs do. On the React side, the low and high values are kept in state as two numbers, and onChange clamps the value so the low value does not go past the high value.

However, this alone causes a problem: when two thumbs overlap at the same value, the thumb cannot be moved to the left. This article covers that fix as well. I built a RangeSlider for selecting a price range and checked how it behaves with the mouse and the keyboard.

Note

The test environment was Ubuntu 24.04, Node.js 22.22.0, and Chromium 153. I used react / react-dom 19.3.1, @types/react 19.3.0, typescript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. I type-checked the .tsx files with tsc, transformed them with esbuild, and then used Playwright to drive Chromium and inspect the values of the two inputs and the range shown on screen. Mouse operations were done with Playwright's page.mouse. I did not test touch input. I did not test Firefox, Safari, mobile browsers, or reading by screen readers.

On a price slider, the low thumb is dragged to 18,000 yen and the high thumb is dragged to 44,000 yen. When the low thumb is dragged to the right past the high thumb, it stops at 44,000 yen. When the overlapping thumb is dragged to the left, the low value moves down to 26,000 yen (the labels in the image are in Japanese)
The range display and the product count change over four drags. Only the frames where a number changed have that display highlighted in pink. (The cursor, the press ring, and the instruction text and count overlay were added for the GIF.)

Two inputs stacked, with the low and high values in state

The whole component is shown below. The low and high values are received from the parent as an array [low, high], and when they change, onChange passes a new array to the parent.

tsx
import { useId, useRef } from 'react';

type Props = {
  label: string;
  min: number;
  max: number;
  step?: number;
  value: [number, number];
  onChange: (value: [number, number]) => void;
  names?: [string, string];
  format?: (n: number) => string;
};

export function RangeSlider({ label, min, max, step = 1, value, onChange, names, format = String }: Props) {
  const [low, high] = value;
  const labelId = useId();
  // true if the two thumbs were overlapping when the high thumb was pressed (until the value first moves)
  const startedOverlapped = useRef(false);
  // true once the thumbs, overlapping, first move to the left. Until the drag ends, the low thumb moves instead of the high thumb
  const moveLowInstead = useRef(false);

  // convert a value into a percentage of the thumb's movable range
  const percent = (v: number) => ((v - min) / (max - min)) * 100;

  function handleLowChange(v: number) {
    // the low value does not go past the high value
    onChange([Math.min(v, high), high]);
  }

  function handleHighChange(v: number) {
    if (startedOverlapped.current) {
      // decide which thumb this drag moves, based on the direction of the first move
      moveLowInstead.current = v < low;
      startedOverlapped.current = false;
    }
    if (moveLowInstead.current) {
      handleLowChange(v);
      return;
    }
    // the high value does not go below the low value
    onChange([low, Math.max(v, low)]);
  }

  function endPress() {
    startedOverlapped.current = false;
    moveLowInstead.current = false;
  }

  return (
    <div className="range" role="group" aria-labelledby={labelId}>
      <div className="range-header">
        <span id={labelId}>{label}</span>
        <span className="range-value">
          {format(low)} 〜 {format(high)}
        </span>
      </div>
      <div
        className="range-track"
        style={{ '--low': `${percent(low)}%`, '--high': `${percent(high)}%` } as React.CSSProperties}
      >
        <input
          type="range"
          min={min}
          max={max}
          step={step}
          value={low}
          name={names?.[0]}
          aria-label={`${label}の下限`}
          aria-valuetext={format(low)}
          onChange={(e) => handleLowChange(Number(e.target.value))}
        />
        <input
          type="range"
          min={min}
          max={max}
          step={step}
          value={high}
          name={names?.[1]}
          aria-label={`${label}の上限`}
          aria-valuetext={format(high)}
          onPointerDown={() => {
            startedOverlapped.current = low === high;
            moveLowInstead.current = false;
          }}
          onPointerUp={endPress}
          onPointerCancel={endPress}
          onChange={(e) => handleHighChange(Number(e.target.value))}
        />
      </div>
    </div>
  );
}

Both inputs receive a value, so both are controlled inputs. As described in React's official reference on controlling an input with a state variable, React keeps the input's value in sync with the value you pass. This behavior is used to write the clamped value back into the input from onChange. As MDN's description of input type="range" explains, the value of a range input is a string that represents a number, so the code converts it with Number() before comparing.

The two refs startedOverlapped and moveLowInstead are used to handle overlapping thumbs. The reasons are explained in a later section.

In the code that uses the component, the price range is kept in state, and the number of products within the range is counted and displayed.

tsx
import { useState } from 'react';
import { RangeSlider } from './RangeSlider';

const PRICES = [1980, 4500, 8800, 12000, 15800, 19800, 24000, 29800, 36000, 42000, 48000];
const yen = (n: number) => `${n.toLocaleString('ja-JP')}円`;

export function App() {
  const [price, setPrice] = useState<[number, number]>([10000, 30000]);
  const [sent, setSent] = useState('');
  const count = PRICES.filter((p) => price[0] <= p && p <= price[1]).length;

  function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const data = new FormData(e.currentTarget);
    setSent(JSON.stringify(Object.fromEntries(data)));
  }

  return (
    <form onSubmit={handleSubmit}>
      <RangeSlider
        label="価格"
        min={0}
        max={50000}
        step={1000}
        value={price}
        onChange={setPrice}
        names={['min_price', 'max_price']}
        format={yen}
      />
      <p className="count">{count}件の商品</p>
      <button type="submit">この条件で探す</button>
      <output className="sent">{sent}</output>
    </form>
  );
}

The results of dragging the thumbs with the mouse in the test environment are shown below. The values moved in steps of 1,000, the value of step, and they also reached both ends, 0 and 50,000.

text
下限のつまみを 10000 → 20000 の位置へドラッグ: 下限 20000 上限 30000 / 表示「20,000円 〜 30,000円」 / 2件の商品
上限のつまみを 30000 → 45000 の位置へドラッグ: 下限 20000 上限 45000 / 表示「20,000円 〜 45,000円」 / 4件の商品
下限のつまみを 20000 → 0 の位置(左端)へドラッグ: 下限 0 上限 45000 / 表示「0円 〜 45,000円」 / 10件の商品
上限のつまみを 45000 → 50000 の位置(右端)へドラッグ: 下限 0 上限 50000 / 表示「0円 〜 50,000円」 / 11件の商品

Making only the thumbs receive clicks

The appearance and click handling are set in CSS. The main rules are shown below.

css
.range-track {
  position: relative;
  height: 28px;
}
/* the line is drawn from inside by the thumb's radius (10px) */
.range-track::before {
  content: '';
  position: absolute;
  left: 10px;
  right: 10px;
  top: 12px;
  height: 4px;
  border-radius: 2px;
  background: linear-gradient(
    to right,
    #d5dde1 var(--low),
    #00c8e8 var(--low),
    #00c8e8 var(--high),
    #d5dde1 var(--high)
  );
}
.range-track input {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  margin: 0;
  appearance: none;
  background: none;
  /* the input box does not receive clicks; only the thumbs do */
  pointer-events: none;
}
.range-track input::-webkit-slider-thumb {
  appearance: none;
  pointer-events: auto;
  width: 20px;
  height: 20px;
  border: 2px solid #00c8e8;
  border-radius: 50%;
  background: #fff;
  cursor: grab;
}

The two inputs overlap in the same place because of position: absolute and inset: 0. The high input is written later, so it is painted on top. Without any change, the high input's box would cover the low thumb.

For that reason, pointer-events: none is set on the inputs, and pointer-events: auto is set on the thumbs. As MDN's description of pointer-events explains, an element with none is not the target of pointer events, and the events reach the element beneath it. The thumb appearance is set with ::-webkit-slider-thumb in Chromium, which I used for testing, and with ::-moz-range-thumb in Firefox. MDN lists both as non-standard pseudo-elements. The CSS I used for testing also includes the same appearance and pointer-events: auto for Firefox, but I did not test Firefox.

I compared the same operations with and without pointer-events: none on the inputs, starting from a low value of 10,000 and a high value of 30,000.

text
pointer-events: none あり(この記事の書き方)
下限のつまみの位置にある要素: 価格の下限
下限のつまみを 10000 → 20000 の位置へドラッグ: 下限 20000 上限 30000 / 表示「20,000円 〜 30,000円」 / 2件の商品
線の上(45000 の位置)をクリック: 下限 20000 上限 30000 / 表示「20,000円 〜 30,000円」 / 2件の商品

pointer-events: none なし
下限のつまみの位置にある要素: 価格の上限
下限のつまみを 10000 → 20000 の位置へドラッグ: 下限 10000 上限 20000 / 表示「10,000円 〜 20,000円」 / 3件の商品
線の上(45000 の位置)をクリック: 下限 10000 上限 45000 / 表示「10,000円 〜 45,000円」 / 7件の商品

Without pointer-events: none, the element at the low thumb's position was the high input. Dragging the low thumb moved the high value from 30,000 to 20,000, and the low value did not move. Clicking on the line moved the high thumb to that position. With the approach in this article, the element at the low thumb's position is the low input, and dragging moves the low value. Clicking on the line where there is no thumb does not change the value. You cannot move a thumb by clicking on the line, so if you want that, you need separate handling.

Aligning the colored line with the thumb centers

The light-blue line between the two thumbs is drawn with linear-gradient in ::before. The percentages computed in the component are passed to the CSS variables --low and --high to set where the blue starts and ends.

If the line is drawn across the full width of the input, the color change is offset from the thumb center by a few pixels. In the Chromium test environment, the range thumb is drawn so that it stays inside the input box both at the minimum and at the maximum value. In this example, the thumb center moves only within the range that starts 10px (the thumb radius) inside each end of the box. By drawing the line starting 10px inside each end as well, the color change lines up with the thumb center.

I checked this with a 360px-wide slider whose thumbs are 20px, by reading pixels in screenshots. At values 0 and 50,000, the thumb center was 10px inside the box edge in both cases. With the low value at 10,000, when the line was drawn across the full width, the blue started 5 to 6px to the left of the thumb center. When the line was drawn starting from the thumb radius inside, the blue started at the thumb center.

Keeping the low value from going past the high value

In handleLowChange, Math.min(v, high) keeps the low value from going past the high value. I checked this by dragging the low thumb to 40,000, which is to the right of the high value.

text
40000 の位置まで動かした(ボタンは押したまま): 下限 30000 上限 30000 / 表示「30,000円 〜 30,000円」 / 0件の商品
ボタンを離した: 下限 30000 上限 30000 / 表示「30,000円 〜 30,000円」 / 0件の商品

Even during the drag, the low input's value stayed at 30,000, and the thumb stopped at the high thumb's position. This is because the clamped value is passed to the parent through onChange, and React sets the input's value back to that value.

With a version that does not clamp the value (passing the received value directly, as in onChange([v, high])), the result was as follows.

text
下限を 10000 → 40000 の位置へドラッグ: 下限 40000 上限 30000 / 表示「40,000円 〜 30,000円」

The low value became greater than the high value, and the range display read "40,000 yen to 30,000 yen", which is reversed. Another approach is to treat the smaller of the two values as the low value. However, in that case, the input named "price low" would hold the high value.

The WAI-ARIA Authoring Practices Guide (APG) section on multi-thumb sliders notes that many sliders have thumbs that cannot pass each other, such as a slider for selecting a range with a low and a high value. The example given is a slider for selecting a price range. The maximum value the low thumb can reach is determined by the high value.

Letting the overlapping thumb also move to the left

When the low value is kept from going past the high value, the two thumbs can end up at the same value and overlap. When they overlap, the high thumb is the one painted on top. If the code only clamps the value, the overlapping thumb cannot be moved to the left in this state. I dragged the overlapping thumb and compared this article's approach with the clamp-only version.

text
この記事の書き方
下限を 30000 まで動かして重ねる: 下限 30000 上限 30000 / 表示「30,000円 〜 30,000円」 / 0件の商品
重なったつまみを左(20000)へドラッグ: 下限 20000 上限 30000 / 表示「20,000円 〜 30,000円」 / 2件の商品
下限を 30000 まで動かして重ねる: 下限 30000 上限 30000 / 表示「30,000円 〜 30,000円」 / 0件の商品
重なったつまみを右(40000)へドラッグ: 下限 30000 上限 40000 / 表示「30,000円 〜 40,000円」 / 1件の商品
キーボードで2つとも右端(50000)にする: 下限 50000 上限 50000 / 表示「50,000円 〜 50,000円」 / 0件の商品
右端で重なったつまみを左(35000)へドラッグ: 下限 35000 上限 50000 / 表示「35,000円 〜 50,000円」 / 3件の商品

越えないようにするだけの書き方
下限を 30000 まで動かして重ねる: 下限 30000 上限 30000 / 表示「30,000円 〜 30,000円」
重なったつまみを左(20000)へドラッグ: 下限 30000 上限 30000 / 表示「30,000円 〜 30,000円」
下限を 30000 まで動かして重ねる: 下限 30000 上限 30000 / 表示「30,000円 〜 30,000円」
重なったつまみを右(40000)へドラッグ: 下限 30000 上限 40000 / 表示「30,000円 〜 40,000円」
キーボードで2つとも右端(50000)にする: 下限 50000 上限 50000 / 表示「50,000円 〜 50,000円」
右端で重なったつまみを左(35000)へドラッグ: 下限 50000 上限 50000 / 表示「50,000円 〜 50,000円」

In the clamp-only version, dragging the overlapping thumb to the left did not move either thumb. The thumb being pressed is the high thumb on top, and the high value cannot be made smaller than the low value. Dragging to the right moves the high value, but when both are overlapping at the right end of 50,000, neither can be moved left or right. The low thumb is hidden under the high thumb, and a mouse cannot grab it.

In this article's approach, when the high thumb is pressed, onPointerDown records in startedOverlapped whether the two were overlapping. If they were, the thumb to move during that drag is decided by the direction of the first movement. If the first movement is to the left, moveLowInstead is set to true. Until that drag ends, the value received from the high input moves the low value. React keeps the high input's value at high, so the high thumb stays where it is, and the low thumb moves under the cursor. The fourth frame of the GIF at the top shows this movement. If the first movement is to the right, the high value moves as before.

The direction is not changed while the button is held down. If the two were not overlapping when the high thumb was pressed, dragging the high thumb left past the low value only makes the high value stop at the low value's position. If you drag the overlapping thumb to the left and then move it back to the right without releasing the button, the low value stops at 30,000, the same as the high value, and the high value does not follow. Conversely, if you drag to the right and then back to the left, the high value stops at 30,000, the same as the low value, and the low value does not move. To move the other thumb, you need to release the button and press again.

text
上限のつまみを 30000 → 5000 の位置へドラッグ: 下限 10000 上限 10000 / 表示「10,000円 〜 10,000円」 / 0件の商品
下限を 30000 まで動かして重ねる: 下限 30000 上限 30000 / 表示「30,000円 〜 30,000円」 / 0件の商品
重なったつまみを 20000 の位置まで左へ(ボタンは押したまま): 下限 20000 上限 30000 / 表示「20,000円 〜 30,000円」 / 2件の商品
そのまま 40000 の位置まで右へ戻す: 下限 30000 上限 30000 / 表示「30,000円 〜 30,000円」 / 0件の商品
下限を 30000 まで動かして重ねる: 下限 30000 上限 30000 / 表示「30,000円 〜 30,000円」 / 0件の商品
重なったつまみを 40000 の位置まで右へ(ボタンは押したまま): 下限 30000 上限 40000 / 表示「30,000円 〜 40,000円」 / 1件の商品
そのまま 20000 の位置まで左へ戻す: 下限 30000 上限 30000 / 表示「30,000円 〜 30,000円」 / 0件の商品

The reason startedOverlapped and moveLowInstead are refs rather than state is that these values are not used for display. As described in the official useRef reference, changing a ref's value does not cause a re-render.

startedOverlapped is set to true only in onPointerDown, so that keyboard operation is excluded. When the thumbs overlap, pressing the left arrow key (ArrowLeft) with the high input focused does not move the high value. If the low input is focused first and the key is pressed, the low value moves.

text
重ねてから、上限にフォーカスして ArrowLeft: 下限 30000 上限 30000 / 表示「30,000円 〜 30,000円」 / 0件の商品
Shift+Tab で下限に移って ArrowLeft: 下限 29000 上限 30000 / 表示「29,000円 〜 30,000円」 / 1件の商品

The end of a drag is handled by onPointerUp and onPointerCancel, which reset the two refs. I also tested dragging the overlapping thumb to the left, moving the cursor outside the input, and then releasing the button. After that, pressing ArrowLeft on the high input, which still had focus, moved the high value from 30,000 to 29,000, not the low value. The refs were reset even though the button was released outside the input.

Keyboard operation and names for screen readers

Both inputs are ordinary <input type="range"> elements, so keyboard operation is handled by the browser. Tab moves focus to the low input and then to the high input. The APG description says that the Tab order should not change even when the thumb values or visual positions change. Because the DOM order stays low, then high, the order does not change in this approach. The keyboard results in the test environment are shown below.

text
Tab: 価格の下限
ArrowRight: 下限 11000 上限 30000 / 表示「11,000円 〜 30,000円」 / 5件の商品
ArrowUp: 下限 12000 上限 30000 / 表示「12,000円 〜 30,000円」 / 5件の商品
ArrowLeft: 下限 11000 上限 30000 / 表示「11,000円 〜 30,000円」 / 5件の商品
PageUp: 下限 16000 上限 30000 / 表示「16,000円 〜 30,000円」 / 3件の商品
End: 下限 30000 上限 30000 / 表示「30,000円 〜 30,000円」 / 0件の商品
Home: 下限 0 上限 30000 / 表示「0円 〜 30,000円」 / 8件の商品
Tab: 価格の上限
Home: 下限 0 上限 0 / 表示「0円 〜 0円」 / 0件の商品
End: 下限 0 上限 50000 / 表示「0円 〜 50,000円」 / 11件の商品

The arrow keys moved the value by step, 1,000 at a time. In Chromium 153, PageUp moved it by 5,000. Pressing End on the low input stopped at 30,000, the same as the high value, not at the maximum of 50,000. Because the value is clamped in onChange, the keyboard and the mouse stop at the same place.

The inputs have aria-label values that mean "price low" and "price high". The whole component is wrapped in role="group", and the label passed as label (the sample uses the Japanese word for "price") is linked to it with aria-labelledby. The accessibility tree read with Playwright is shown below.

text
- group "価格":
  - text: 価格 10,000円 〜 30,000円
  - slider "価格の下限": "10000"
  - slider "価格の上限": "30000"

aria-valuetext is set to a string with the unit, such as "10,000 yen". As described in MDN's explanation of aria-valuetext, when aria-valuetext is present, that string is read out in place of the numeric value.

I could not confirm whether this string is actually read aloud. I did not test with a screen reader. In the Chromium accessibility tree I read with Accessibility.getFullAXTree from the Chrome DevTools Protocol, the valuetext of the slider items did not include the aria-valuetext string. A role="slider" div that I also placed for comparison did not show it either, so I could not judge from these values whether it is read aloud.

One more point: the APG section on multi-thumb sliders says that a slider whose movable range depends on the other value should update aria-valuemin and aria-valuemax whenever the value changes. The component in this article keeps min and max of both inputs at 0 and 50,000, so it does not follow this. When the low value was 20,000, the low thumb's valuemax in getFullAXTree was 50,000, not 30,000, which is where it actually stops. To follow the APG, you would update the low input's aria-valuemax and the high input's aria-valuemin to match the other value. I have not tested that approach in this article, so if you build it, check the values that appear in the accessibility tree.

Submitting the form passes both values through as-is

Both inputs have a name, so their values are sent as form values. With the low value set to 15,000 and the submit button pressed, the contents of FormData were as follows.

text
送信された値: {"min_price":"15000","max_price":"30000"}

Both values are strings, so the receiving side has to convert them to numbers before comparing.

​Posted by 86