Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.scrollTo() in react components?

Tags:

reactjs

Where do I have to put the window.scrollTo(0,0) call in a react component?

I tried to put it directly into render and also tried componentDidUpdate (to wait till everything is rendered), but somehow the scrollbars always stay at the same position.

-- Edit --

The problem was CSS height/overflow of the window and body.

See: https://stackoverflow.com/a/18573599/1016383

like image 723
K.. Avatar asked Jun 29 '15 15:06

K..


People also ask

How do I use Windows scrollTo in Reactjs?

scrollTo only works when the scroll behavior is set on html . If you have set overflow: scroll on some container inside of the DOM, then that need to be accessed. Assign an id to that. For example I have below div container for which I have set overflow: scroll .

How do I scrollTo the top of the component in React?

Use the window. scrollTo() method to scroll to the top of the page in React, e.g. window. scrollTo(0, 0) . The scrollTo method on the window object scrolls to a particular set of coordinates in the document.

How do you scroll page to particular DIV in React?

To scroll to an element on click in React:Set a ref prop on the element you want to scroll to. Set the onClick prop on the other element. Every time the element is clicked, call the scrollIntoView() method on the ref object.


2 Answers

Well, window.scrollTo(0,0) would always stick to the top of the page.

You are correct in saying this code should live in the componentDidMount function, but you need to tell it where to scroll. I would locate the id of the element you want to scroll to and obtain it's y coordinates, than you enter that into the window.scrollTo and it should work. You may need to get the height of the component and add that to this dymamic value you obtained.

like image 165
Chris Hawkes Avatar answered Sep 21 '22 05:09

Chris Hawkes


window.scrollTo only works when the scroll behavior is set on html.
If scroll is set on body then document.querySelector("body").scrollTo(0,0)

If you have set overflow: scroll on some container inside of the DOM, then that need to be accessed. Assign an id to that. For example I have below div container for which I have set overflow: scroll.

<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <div id="root">
      <div id="scroller">
        <!-- other content -->
      </div>
    </div>    
  </body>
</html>

Then for scrolling behavior, you need to query the scroller.

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

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

This would work perfectly.

like image 21
Puspender Avatar answered Sep 18 '22 05:09

Puspender