Control the material-ui slider with a play and stop buttons in React JS

I am using the continuous slider from metrial-ui in ReactJS project. I want to control the slider such that when click on the play button the slider start moving and stops when clicking stop.below is the code of the slider.

   const useStyles = makeStyles({
  root: {
    width: 200,
  },
});
         
<div className={classes.root}>
      <Typography id="continuous-slider" gutterBottom>
        Volume
      </Typography>
      <Grid container spacing={2}>
        <Grid item>
          <VolumeDown />
        </Grid>
        <Grid item xs>
          <Slider value={value} onChange={handleChange} aria-labelledby="continuous-slider" />
        </Grid>
        <Grid item>
          <VolumeUp />
        </Grid>
      </Grid>

Thanks in advance

Answer

This can be done by calling setState to update the Slider value after an interval. You’ll need to use useEffect to create and clean up the interval callback when the isRunning state changes:

export default function ContinuousSlider() {
  const [value, setValue] = useState<number>(30);
  const [isRunning, setIsRunning] = useState(false);
  const directionRef = useRef<"back" | "forward">("back");
  const intervalIdRef = useRef(0);

  const handleChange = (event: any, newValue: number | number[]) => {
    setValue(newValue as number);
  };
  const handleBack = () => {
    directionRef.current = "back";
    if (!isRunning) {
      setIsRunning(true);
    }
  };
  const handleNext = () => {
    directionRef.current = "forward";
    if (!isRunning) {
      setIsRunning(true);
    }
  };
  const handleStop = () => {
    setIsRunning((r) => !r);
  };

  useEffect(() => {
    if (isRunning) {
      intervalIdRef.current = setInterval(() => {
        if (directionRef.current === "forward") {
          setValue((v) => ++v);
        }
        if (directionRef.current === "back") {
          setValue((v) => --v);
        }
      }, 16);
    }

    return () => clearInterval(intervalIdRef.current);
  }, [isRunning]);

  return (
    <>
      <IconButton onClick={handleStop}>
        <StopIcon />
      </IconButton>
      <IconButton onClick={handleBack}>
        <ArrowBackIcon />
      </IconButton>
      <IconButton onClick={handleNext}>
        <ArrowForwardIcon />
      </IconButton>
      <Slider value={value} onChange={handleChange} />
    </>
  );
}

Live Demo

Edit 66983676/control-the-material-ui-slider-with-a-play-and-stop-buttons-in-react-js