Get MUI Slider value in onDragStop event

Viewed 21754

I want to fire an event onDragStop rather than onChange using a MUI Slider in my React app (so that the event fires fewer times). However, the documentation indicates that the onDragStop function signature only has the mouseevent: function(event: object) => void. So, the following works with onChange:

<Slider onChange={ (e, val) => this.props.update(e, control.id, val) }  />

However, this event doesn't have a second parameter val:

<Slider onDragStop={ (e, val) => this.props.update(e, control.id, val) }  />

How can I get the current value of the Slider in the onDragStop function? Note, I'm unable to use this, as it refers to the parent component.

5 Answers

In a newer version of Material UI you could use:

<Slider
  onChange={} // for example updating a state value
  onChangeCommitted={} // for example fetching new data
/>
<Slider
  // invoked when the user drags the thumb
  onChange={(_, newValue) => update(newValue)}
  // invoked when the user drops the thumb
  onChangeCommitted={(_, newValue) => update(newValue)}
/>

Live Demo

Codesandbox Demo

I know this is super late, but I wanted to add my two cents:

If all you need is to not constantly fire an event, you can use debouncing like this:

const handleSliderChange = useCallback((event, value) => {
debounceSliderChange(value);
}, []);

const debounceSliderChange = debounce((val) => {
setValue(val)
}, 200);

and then:

<Slider onChange={(e, v) => handleSliderChange(e, v)}/>

For reference, I am importing debounce from: "@mui/material/utils"

Demo:

https://codesandbox.io/s/festive-dirac-fij37p?file=/src/App.js

Related