I have a component, which I'd like to keep the scroll position each time it re-renders.
Therefore I have created a useState for it's position. Inside the useEffect, I've created an intervall, which will track the current position every x seconds and set it using setState.
It seems to be working fine to this point, because when I console log the state (scrollTop) inside the useEffect, I get the updated numbers.
I keep track of the element by setting it as a ref with useRef.
const [scrollState, setScrollState] = useState(0);
const element = useRef<HTMLDivElement>(null);
useEffect(() => {
console.log(scrollState);
const captureElementScroll = setInterval(() => {
if (element.current) {
const scrollTop = _.get(element.current, "scrollY");
setScrollState(scrollTop);
}
}, 2000);
if (element.current && element.current) {
element.current.scrollTo({
behavior: "smooth",
top: scrollState
});
}
return () => {
clearInterval(captureElementScroll);
};
}, [scrollState]);
Now the problem is, each time this component gets re-rendered, the current state is set back to zero.
Maybe a problem with the parent components? I'm out of ideas. Am I doing it the correct way?
scrollTo()
usingscrollState
is, when the element is supposedly already at that scroll position. – Patrick Robertsif (element.current && element.current)
and_.get(element.current, "scrollY")
make no sense to me. – marzelin