Material-ui: Reset slider to default values of min and max

Viewed 1177

I have a double sided slider component, that I created using @material-ui/core/Slider based on their documentation on customized slider

This is what the slider looks like when it first renders

enter image description here

When I slide the slider the numbers change, these numbers are are stored in redux and are passed to the text components, but not the slider itself, as I want to prevent a rerender of the slider every time the numbers change

enter image description here

When I reset the numbers to their original values though, I would like the slider handles to reset to their original positions. This would mean the slider would look the same as it does in the top picture after resetting. They do not however, this is what my slider looks like when I try to reset.

enter image description here


I reset my values when a button is clicked. The onClick of this button dispatches an action that sets the min and max values(those in the text) to their defaults. This is the same dispatcher that my slider onChange calls. I also call a dispatcher that changes a value called reRender to true, which my slider is supposed to be watching. This dispatcher is also called when this button is click.

The component below is my Slider component. A few parts are commented out. If I uncomment the alert('if'), the alert displays only after I click the button that is supposed to reset my slider, and then it displays every time I adjust my slider. The useEffect does nothing if I uncomment it, but was an attempt to solve this problem. If I change let value to let value=[min,max]then my slider gets permanently stuck at 0k and 250k, which means that setting the value has an effect on the slider handles, but when the value is set within the if block for some reason.

You can view a similar slider at this codesandbox, but it does not have a reset button and does not use redux.

2 Answers

I'm not sure if this is the answer, but I think your problem may have something to do with you setting value to [min, max] instead of fixed numbers.

This was a similar problem I recently tackled recently. If this is an anti-pattern, someone please correct me!

You can use the key prop to reset the component to its initial state.

let resetCount = 0

export default function App() {
  const [sliderVals, setSliderVals] = useState({})

  // Some state building logic
  //...

  const resetForm = () => {
    resetCount += 1
  }

  return (
    <>
      <SliderComponent key={resetCount} sliderVals={sliderVals} />
      <Button onChange={resetForm} />
    </>
  )
}
Related