Part 1 - Throttling Event Handler
Your first issue is caused by the way you are using _.throttle()
, it should ideally be wrapped around your event handler callback.
Please review the examples in lodash.throttle() docs
for reference on usage.
Also have a look at this SO question it may offer you some more insight into using throttle within React Hooks.
The key change was to wrap the event callback with throttle
.
const throttledSetPosition = throttle(event => {
if (event.touches[0].clientY) {
if (slider.current.contains(event.target)) {
setTouchPosition(Math.round(event.touches[0].clientY));
}
} else {
setTouchPosition(null);
}
}, 200);
const handleTouchMove = useCallback(throttledSetPosition, [touchPosition]);
Part 2 - Increasing/Decreasing Value
To achieve your goal of increasing/decreasing the displayed value, you first need to identify a scale. What is the max-min you want displayed? Let's use 100
as that is easily understood.
What you then need to calculate is the percentage of 100
the user is currently touching at, but reversed (since closer to the top is really closer to 100
and further down is closer to 0
).
To do this you could use the following:
// Define the scale
const scale = 100;
// Extract needed variables from event touches array
const {
clientY,
target: { offsetHeight, offsetTop }
} = event.touches[0];
// Calculate the percentage
const percentage = (clientY - offsetTop) / offsetHeight;
// Make the calculation to be reversed by subtracting the percentage from the scale...
const currentValue = scale - (percentage * scale);
// Set the display value
setTouchPosition(Math.round(currentValue));
I have forked your sandbox here with the above alterations.