0
votes

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?

1
It seems like the parent components are the ones with the issue, nothing in this code indicates an issue with data flow that I can see. Though I am curious what the purpose of scrollTo() using scrollState is, when the element is supposedly already at that scroll position.Patrick Roberts
if (element.current && element.current) and _.get(element.current, "scrollY") make no sense to me.marzelin
@PatrickRoberts maybe some more context what I tried: it's an iframe that changes its content, and when pressing a refresh button I want it to jump back to its previous position. But I guess the problem lies in my structure then. I should probably make the refresh button directly refreshing the iframe and not its parent container.josias
@marzelin correct! It had its purpose in the original code, I forgot to remove it when I abstracted it :Pjosias

1 Answers

0
votes

Now looking back to this issue (I have discontinued what I was working on ), I'm pretty sure that I captured the scroll position on the wrong level.

Like I guessed already, the problem was that the Parent component got re-rendered and therefore the state got lost.

Maybe I'll work on something similar at some point. If so I'll write a more detailed answer.