I have a MUI slider where the value of the slider needs to be inverted based on a boolean variable. My current code inverts it correctly but it also inverts the drag functionality, meaning if I tried to drag my slider towards 0, it would move towards 100 instead. I can’t think of a workaround to correct this. Would appreciate if anyone has any suggestions I could try.
const handleSelectionChange = (e: any) => {
if (typeof e.target.value === 'string') {
onChange(e.target.value)
} else {
onChange(Number(e.target.value))
}
}
<Slider
aria-label='DiceRoll'
defaultValue={50}
valueLabelDisplay='auto'
step={1}
min={0}
max={100}
value={overUnder ? 100 - targetNumber : targetNumber} //overUnder is boolean and targetNumber ranges from 0 to 100.
marks={marks}
onChange={handleSelectionChange}
/>
2
Answers
So after a few hours I've found the solution, it's actually a pretty simple solution, just an additional 3 lines of codes. We just have to introduce another state which only purpose is to display the correct slider Value.
basically what this does is, when overUnder = true, and when it's true, the slider would just work normally. when it is flipped and overUnder = false, onChange will update targetNumber to inverse [which is needed for other components]. and setFlippedTargetNumber will be used as slider Value instead of targetNumber.
Hope this helps anyone who is facing a similar problem. :)
Using the
valueLabelFormat
function, you can simply format the number display instead of the number value itself, preventing the problem.Use this instead:
valueLabelFormat={(v) => (overUnder ? 100 - v : v)}
Set the value back to normal:
value={targetNumber}
Also a sandbox for reference.