1

I have a multipage application. I need to implement scroll to top automatically when I traverse to a new page. I have tried following:

ScrollToTop.js this is placed inside component folder

import React, { Component } from 'react';
import { withRouter } from 'react-router';

class ScrollToTop extends Component {
  componentDidUpdate(prevProps) {
    if (this.props.location !== prevProps.location) {
      window.scrollTo(0, 0)
    }
  }

  render() {
    return this.props.children
  }
}

export default withRouter(ScrollToTop)

And App.js

import {Router} from 'react-router-dom'
import ScrollToTop from './common/components/ScrollToTop'
const Appnew = () => (
  <Router>
    <ScrollToTop>
      <Appnew/>
    </ScrollToTop>
  </Router>
)
const App = (props) => {
{Appnew()}
}

This is not working. Any suggestions?

ReactUser
  • 11
  • 2
  • Possible dublicate of [Scroll to the top of the page after render in react.js](https://stackoverflow.com/questions/33188994/scroll-to-the-top-of-the-page-after-render-in-react-js) – Thielicious Jun 16 '20 at 13:53

2 Answers2

1

There is nothing wrong in your hoc. Assuming your Appnew has components encapsulated with Route, it should work.

Just used your hoc and prepared a demo which is working fine. Take a look.

gdh
  • 13,114
  • 2
  • 16
  • 28
0

You should try to change this

  componentDidUpdate(prevProps) {
    if (this.props.location !== prevProps.location) {
      window.scrollTo(0, 0)
    }
  }

by

componentDidMount() {
      window.scroll({
        top: 0,
        left: 0
     });
 }

What it will do it's when the component is mounted it will scroll to the top.

Also you could use the event below which listen the DOM and when it is loaded do whatever you want to

window.addEventListener('DOMContentLoaded', (event) => {
    // Your code
});
crg
  • 4,284
  • 2
  • 29
  • 57