In react, how to detect when the thumb of the range slider is clicked?

Viewed 440
<input
  ref={left_slider}
  onClick={() => set_neg_clicked(!neg_clicked)}
  step={100}
  type="range"
  min={-1000}
  max={neg_side_max}
  value={neg_side_val}
  onChange={(e) => set_neg_side_val(Math.min(900, e.target.value))}
  className="slider left"
  id="my_neg_range"
  style={{
    margin: 0,
    width: `${neg_side_width}px`,
    position: "absolute",
    left: 0,
    zIndex: 2,
  }}
  ></input>

I need to know when the thumb is clicked. So how can the thumb be accessed in React?

1 Answers

It's an interesting question and the straight answer to that is it's not directly accessible. You have a few options though.

  1. Use a completely different slider other than the input slider.
  2. Add 2 events onClick and OnInput on the input. When you click anywhere in the slider except the thump, your onInput is going to run. onInput is going to run first then the onClick in case the value is changing. When you just click the thump, onInput won't run, only onClick will get triggered.

The limitation is when you click and not leave the mouse, that's not a complete click.

Here is my crazy idea as code,

import React, { useState, useRef } from 'react';

export default function App() {
  const [value, setValue] = useState(1);
  let clickRef = useRef(false);
  return (
    <input
      type="range"
      min="1"
      max="100"
      value={value}
      onInput={e => {
        setValue(+e.target.value);
        clickRef.current = true;
      }}
      onClick={e => {
        if (!clickRef.current) console.log('Clicked thump');
        clickRef.current = false;
      }}
    />
  );
}

I used useRef to hold a value, not as an element ref. Changing the value of ref won't trigger a re-render.

Related