0

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.

Alsakka
  • 155
  • 10
  • Does the `scrollTo` work if you move it outside of the `useEffect`? Is there a reason this must happen on-render? It seems to make more sense to move this to the place that decides to render this Component. – Halcyon Sep 05 '22 at 14:47
  • are those 2 components the same component? like do you have 2 Terms pages? – SlothOverlord Sep 05 '22 at 14:48
  • No they are Terms and About, both running from Parent component under same Routes but they each have own Router – Alsakka Sep 05 '22 at 14:51
  • I took the scrollTo outsude useEffect and still the same issue @Halcyon – Alsakka Sep 05 '22 at 14:52
  • Does `window.scrollTo(0, 0);` work at all? There might be CSS reasons why the scroll isn't happening. Maybe the window can't scroll. – Halcyon Sep 05 '22 at 14:54
  • yes it works only if I click refresh button, but switching between Routes does not make it work – Alsakka Sep 05 '22 at 15:08
  • ```window.scrollTo(0, 0)``` works also if I have it inside a ```button``` as an ```onClick``` event @Halcyon – Alsakka Sep 05 '22 at 15:14
  • An `useEffect(..., [])` is equivalent to `componentDidMount` & is called once when the component is mounted. Are you sure the 'effect rendered' is printed each time ? – Nice Books Sep 05 '22 at 17:30
  • Yes each time it was rendered, I had another ```console.log``` with different text in the other component and both with rendering each time. @NiceBooks – Alsakka Sep 05 '22 at 19:38
  • Inspect to check if there are ` – Nice Books Sep 06 '22 at 05:37
  • There arent any ``` – Alsakka Sep 06 '22 at 10:43
  • See https://stackoverflow.com/questions/31119786/window-scrollto-in-react-components?noredirect=1&lq=1 – Nice Books Sep 06 '22 at 10:55

2 Answers2

1

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!

Alsakka
  • 155
  • 10
0

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.

Konflex
  • 465
  • 3
  • 11