Skip to content
Advertisement

Change image according to value of MaterialUI slider

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?

JavaScript
JavaScript
JavaScript

Thanks a lot!

Advertisement

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); };.

Advertisement