Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll to the top of the page after render in react.js

People also ask

How do I change the scroll position in React?

To get scroll position with React, we can add a scroll listener to window . to create the scrollPosition state with the useState hook. Then we add the handleScroll function that takes the scroll position with the window.

How do I use scrollTo in Windows React?

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 you scrollTo a particular section in React?

React 16.3 +, Class component myRef}>Element to scroll to</div> } executeScroll = () => this. myRef. current. scrollIntoView() // run this method to execute scrolling. }


Finally.. I used:

componentDidMount() {
  window.scrollTo(0, 0)
}

EDIT: React v16.8+

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

Since the original solution was provided for very early version of react, here is an update:

constructor(props) {
    super(props)
    this.myRef = React.createRef()   // Create a ref object 
}

componentDidMount() {
  this.myRef.current.scrollTo(0, 0);
}

render() {
    return <div ref={this.myRef}></div> 
}   // attach the ref property to a dom element

You could use something like this. ReactDom is for react.14. Just React otherwise.

    componentDidUpdate = () => { ReactDom.findDOMNode(this).scrollIntoView(); }

Update 5/11/2019 for React 16+

  constructor(props) {
    super(props)
    this.childDiv = React.createRef()
  }

  componentDidMount = () => this.handleScroll()

  componentDidUpdate = () => this.handleScroll()

  handleScroll = () => {
    const { index, selected } = this.props
    if (index === selected) {
      setTimeout(() => {
        this.childDiv.current.scrollIntoView({ behavior: 'smooth' })
      }, 500)
    }
  }

In React Routing there is the problem that if we redirect to the new route, then it won't automatically take you to the top of the page.

Even I did have the same issue.

I just added the single line to my component and it worked like butter.

componentDidMount() {
    window.scrollTo(0, 0);
}

Refer: react training


For those using hooks, the following code will work.

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

Note, you can also import useEffect directly: import { useEffect } from 'react'