Home > database >  How to make range input's "onChange" only trigger when user releases the slider?
How to make range input's "onChange" only trigger when user releases the slider?

Time:01-31

I'm trying to add a simple slider to my React code which will update the component's state. The below code works fine, but it triggers constantly as the user drags the slider. How can I make it so that "setSmoothness" only triggers after the user releases the slider?

    setSmoothness(smoothing) {
        this.setState({
            smoothing: smoothing
        })
    }

    render () {
        <input value={smoothing} onChange={e => this.setSmoothness(e.target.value)} type="range" name="smoother" min="0" max="100" />
    }

CodePudding user response:

There's an easy fix to this, which is to not make it a controlled component. You can hold the state in the same component. Just don't hook it up to the input. The DOM methods for range only fires when you let go of the slider. So that should solve your case instantly.

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

export function App(props) {
  const [val, setVal] = useState(20);
  const inputRef = useRef();

  useEffect(()=>{
    inputRef.current.addEventListener('change', e => setVal(e.target.value))
  },[])
  return (
    <div>
      <input ref={inputRef} type="range" />
    </div>
  );
}
  • Related