ScrollTo inside useEffect react component is not working

1.4k Views Asked by At

I am trying to scroll to the top on a component when its being rendered. My code looks like this:

const Terms = () => {
  
  useEffect(() => {
    window.scrollTo(0, 0);
    console.log("effect rendered");
  }, []);
  
return <>...</>

when I switch between 2 components it does not scroll to the top of the component. Even though console.log renders each time as expected but not the scroll.

3

There are 3 best solutions below

0
Alsakka On BEST ANSWER

The solution that worked for my problem is:

  useEffect(() => {
     const element = document.getElementById('someId');
     element.scrollIntoView();
  }, []);
  return (<div id="someId"> ... </div>)

Thanks for everyone still for the ideas!

2
Konflex On

I found a conversation and it seem that you have to give an id to the element you want to scroll to:

window.scrollTo() in react components?

Your element:

<div id="scroller">

const scrollToTop = () => {
  document.getElementById("scroller").scroll(0,0)
}

<button onClick={scrollToTop}>Scroll to Top</button>

Put the scrollTop inside you useEffect() and it should work.

0
mikestarace On

For me, the problem came from my App.css file where I had set scroll-behavior: smooth; for all elements.

To make it so that the page will instantly go to the top, I had to specify in the scrollTo function that I wanted the scroll behavior to be instant. See this fix:

useEffect(() => {
    window.scrollTo({
      top: 0,
      left: 0,
      behavior: "instant",
    });
  }, []);

However, if you do want the smooth scrolling effect, the following code will achieve that.

useEffect(() => {
    setTimeout(() => window.scrollTo(0, 0), 100);
  }, []);

App.css

*{
  scroll-behavior: smooth;
}