Change image according to value of MaterialUI slider

Tags: , ,



I would like to use a discrete Slider component from Material UI to change a picture in a React web app: every time the user changes the value on the slider, a different picture should be displayed in a specified div. How can I do it? I guess that this starts with invoking a handleChange function in onChange within the Slider component, but how could I move forward?

const {Slider, Typography} =  MaterialUI

function App() {
  const [value, setValue] = React.useState([20, 30])
  const handleChange = (event, newValue) => {
        setValue(newValue);
  }
  return (
    <form>

      <Slider
        defaultValue={30}
        aria-labelledby="discrete-slider"
        valueLabelDisplay="auto"
        step={10}
        marks
        min={10}
        max={100}
      />
      
      <Typography>state value: {JSON.stringify(value)} </Typography>

    </form>
  )
}
    
    
// boilerplate to init the app    
ReactDOM.render(<App/>, document.getElementById('main'))
#main { margin-top: 15% }
<script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@material-ui/core@latest/umd/material-ui.development.js"></script>

<main id="main"></main>

Thanks a lot!

Answer

TL;DR: You need to listen to slider events like onChangeCommitted={handleChange}.

NL;PR: I modified your code with a slider changing the URL text on slide events here. You have to make your Slider controlled (the state is managed externally: const [value, setValue] = React.useState(1);). Now you provide the current value value={value} and decide when to update it like when the user interacts with it onChange={handleChange} (any slide change) or onChangeCommitted={handleChange} (only the last change after the user let go of the slider). Finally, you can obtain the user selection from newValue as you already set in this callback: const handleChange = (event, newValue) => { setValue(newValue); };.



Source: stackoverflow