简体   繁体   中英

Need scroll to be at top on new page load - React

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?

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
});

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM