javascriptreactjsmaterial-uislider

Material UI React Slider Component Not Working on mobile


I have been trying to add Slider component to a react project. functionality wise its working fine but i am having two issues which i am not able to get rid of

  1. changing value of the slider is not smooth. Dragging doesn't work properly, its just drags to the nearest value and then stops.
  2. On a mobile device its even worse, no dragging at all, i have to tap on the exact spot for the slider to move.

I did find the issue, i was using onChange, so when i removed it it worked exactly like the example. But i need to update state of parent component, so added line 18, but then again the same issue appeared. I fi remove line 18 then all this gets fixed but i need line 18 to call a function of parent component, to update its state variable.

Here is the gist link of my code https://gist.github.com/kapiljhajhria/0e9beda641d561ef4448abf9195dbcca

 import React from "react";
import Slider from "@material-ui/core/Slider";

export default function SliderWithLabel(props) {
    const {
        labelText, range = {
            min: 0,
            max: 10
        }, step = 1,
        // defaultValue = Math.ceil((range.min + range.max) / 2),
        handleSliderChange,
        name,
        value: sliderValue
    } = props;

    function sliderValuetext(value) {
        // handleChange({target: {value: value}});
        if(value!==sliderValue)handleSliderChange(value,name)
        return `${value}`;
    }
    return (
        <div className="sliderField" style={{display: "flex", flexDirection: "column"}}>
            <div>
                {labelText}
            </div>
            <Slider
                style={{width: "90%", justifyContent: "center", display: "flex", margin: "auto"}}
                    defaultValue={sliderValue}
                    getAriaValueText={sliderValuetext}
                    aria-labelledby="discrete-slider"
                    valueLabelDisplay="auto"
                    // onChange={sliderChange}
                    step={step}
                    // name={name}
                // onChange={handleChange}
                    marks
                    min={range.min}
                    max={range.max}
            />
        </div>
    )
}

Solution

  • after spending 2 days on the issue, creating a sample project , trying to recreate the issue , it turned out to be a simple fix. Parent component has a FORM, key which i was using for the form was

    Date().getTime()
    

    This was what was causing the issue with the slider. My guess would be that it was rebuilding the whole form with each slider value change. Which made slider UI behave in such a way. using appropraite key fixed the issue. I am now switching between two key value.