0

I'm following the second answer to implement a scroll to top every time there's a route change. The answer suggests creating a new component, <ScrollToTop />, which I did

import { useEffect } from 'react';
import { withRouter } from 'react-router-dom';

function ScrollToTop({ history }) {
  useEffect(() => {
    const unlisten = history.listen(() => {
      window.scrollTo(0, 0);
    });
    return () => {
      unlisten();
    }
  }, []);

  return (null);
}

export default withRouter(ScrollToTop);

I'm confused as to where to place such component, since my app is structured a bit differently. See the index.js and App.js files below.

index.js

ReactDOM.render(
  <>
    <EWLoader />
    <ContextProvider>
      <Router>                       //tried placing below <Router>, didn't work
        <App />
      </Router>
    </ContextProvider>
  </>,
  document.getElementById('root'),
)

App.js

function App() {
  return (
    <>                                    //tried placing above <Switch>, didn't work
      <Switch>
        <Route path="/EWadmin">
          <Admin />
        </Route>
        <Route path="/ewadmin-allbookings">
          <AdminAllBookings />
        </Route>
        <Route path="/">
          <EWHeader />
          <Middleware />
          {/* <EWPopular /> */}
        </Route>
      </Switch>
    </>
  )
}

I've also noticed <ScrollToTop /> is destructuring an object's property history but I'm not importing or declaring it anywhere in index.js or App.js. Perhaps something should be done with regards to that?

uber
  • 4,163
  • 5
  • 26
  • 55

1 Answers1

0

There are two ways to achieve scrolling to top on page change:

First solution

Modify your ScrollToTop component to this:

function ScrollToTop({ history }) {
  useEffect(() => {
    const unlisten = history.listen(() => window.scrollTo(0, 0));
    return unlisten;
  }, [history]); // make sure to list history as a dependency

  return null;
}
export default withRouter(ScrollToTop);

Then add ScrollToTop just under your router. Now it scrolls to top anytime the history changes, for any page.

Second solution

Modify your ScrollToTop component:

function ScrollToTop() {
  useEffect(() => {
    window.scrollTo(0, 0);
  }, []); // No dependency

  return null;
}
// No need to use withRouter

Then add ScrollToTop under every Route component where you want this behaviour.

Louis Coulet
  • 3,663
  • 1
  • 21
  • 39
  • I'd like to add that I also deleted smooth scrolling from the css properties to make it work – uber Sep 11 '20 at 13:47