TheoG
TheoG

Reputation: 1558

Why does window.scrollTo action only fire on initial page load?

So I want a scroll action to take place every time my component is called, which it does if I load the component directly. But if I navigate to the component from elsewhere, then the scroll process does not work. Why?

const scrollToRef = (ref) => window.scrollTo(0, ref.current.offsetTop);

const OrderList = props => {
  const topRef = useRef(null);

  useEffect(() => {
    scrollToRef(topRef);
  },[]);

  return (
    <>
    <div style={{height:1500}} />
    <div ref={topRef} id="top">I wanna see.</div>
    </>
  );
}

Upvotes: 0

Views: 276

Answers (3)

Meir
Meir

Reputation: 14395

It is probably race condition, the effect is called on component initialization, the ref is set later. A better approach would be:

const scrollToComp = el => el && window.scrollTo(0, el.offsetTop);

and then

<div ref={scrollToComp}>...</div>

Upvotes: 1

Vencovsky
Vencovsky

Reputation: 31683

But if I navigate to the component from elsewhere, then the scroll process does not work. Why?

Because the navigation isn't rerendering the component.

You need to pass some prop of the navigation on the useEffect so when the navigation change the page, it runs the effect again.

Please especify what navigation you are using.

Upvotes: 0

Clarity
Clarity

Reputation: 10873

If you pass an empty array to useEffect as a second argument, it won't track any variables from the component and fire the function inside it only once.

More info in the official React docs.

Upvotes: 0

Related Questions