Closed fostimus closed 1 year ago
Hi Derek, thank you for pointing out the lack of the proper ref
behavior of the React wrapper. I will try to fix that.
You're right about using onSlide
prop to get the slider position, and value
prop to set it. onSlide
is fired by the component's animation cycle. It does it quite often. Thus, updating the component's state on every onSlide
event will cause a lot of reconciliation cycles, especially when a user is using the keyboard. To mitigate that, I suggest using a form of "debounce." In the following example, we will set the component's value only after the slide animation has finished:
import { ImgComparisonSlider } from '@img-comparison-slider/react';
import { useCallback, useRef, useState } from "react";
function App() {
const [value, setValue] = useState(50);
const completionTimerRef = useRef(null);
const onSlide = useCallback((event) => {
if (completionTimerRef.current) {
clearTimeout(completionTimerRef.current);
}
completionTimerRef.current = setTimeout(() => {
console.log(`The slide animation has finished. The value is ${event.target.value}`);
setValue(event.target.value);
}, 100);// ⤵
// Let's assume that the user has finished sliding the slider
// when the onSlide event is not called for 100ms
}, [completionTimerRef, setValue])
return (
<ImgComparisonSlider value={value} onSlide={onSlide}>
<img slot="first" src="https://img-comparison-slider.sneas.io/demo/images/before.webp" />
<img slot="second" src="https://img-comparison-slider.sneas.io/demo/images/after.webp" />
</ImgComparisonSlider>
);
}
I hope this helps. Please let me know if you have more questions regarding the usage of this library. I appreciate that you checked out the source code 👍
:tada: This issue has been resolved in version @img-comparison-slider/react-v8.0.1 :tada:
The release is available on:
Your semantic-release bot :package::rocket:
Hi Derek, the ref issue is fixed. Here is how you can use ref in case of Typescript
import { useRef } from 'react';
import { HTMLImgComparisonSliderElement, ImgComparisonSlider } from '@img-comparison-slider/react';
function App() {
const sliderRef = useRef<HTMLImgComparisonSliderElement>(null);
return (
<ImgComparisonSlider ref={sliderRef}>
<img slot="first" src="https://img-comparison-slider.sneas.io/demo/images/before.webp" />
<img slot="second" src="https://img-comparison-slider.sneas.io/demo/images/after.webp" />
</ImgComparisonSlider>
);
}
export default App;
Feel free to reopen the issue or create a new one in case of any problem.
In React world, we can use a components methods via a ref. A ref that has a way to programmatically move the handle would be awesome, right now I'm getting the position via the
onSlide
prop and setting back to what I want in thevalue
prop. Which is causing more renders than needed :/