Prevents unwanted MUI Slider changes while scrolling on a mobile device.
First npm i mui-scrollable-slider-hook react react-dom @mui/material @emotion/styled @emotion/react
.
Then when you want to prevent slider values from changing while scrolling on your phone:
import Slider from '@mui/material/Slider'
import { useMuiScrollableSlider } from 'mui-scrollable-slider-hook'
const App = () => {
const { ref, value, onChange, onChangeCommitted } = useMuiScrollableSlider()
return (
<Slider
ref={ref}
value={value}
onChange={onChange}
onChangeCommitted={onChangeCommitted}
/>
)
}
The hook supports an options
object:
value
The initial Slider value. Default is0
.delta
The range over which the y-coordinate of touch points can vary from start touch to end touch. SeeTouch.pageY
. Default is50
.onChange
Callback executed when the Slider value changes.onChangeCommitted
Callback executed when themouseup
ortouchend
event fires on the Slider.
It can be used like this:
const { ref, value, onChange, onChangeCommitted } = useMuiScrollableSlider({
value: 15,
delta: 25,
onChange: (evt, value, activeThumb) => {
console.log('onChangeCallback', evt, value, activeThumb)
},
onChangeCommitted: (evt, value) => {
console.log('onChangeCommittedCallback', evt, value)
}
})
return (
<Slider
ref={ref}
value={value}
onChange={onChange}
onChangeCommitted={onChangeCommitted}
/>
)
Or made reusable:
import Slider from '@mui/material/Slider'
import { useMuiScrollableSlider } from 'mui-scrollable-slider-hook'
const MobileSlider = ({
delta = 50,
value = 0,
onChange = () => {},
onChangeCommitted = () => {},
...rest
}) => {
const hookProps = useMuiScrollableSlider({
delta,
value,
onChange,
onChangeCommitted
})
return <Slider {...hookProps} {...rest} />
}
export { MobileSlider }
See it on CodeSandbox.