Solution 1: Using useEffect Hook (React Router v5 or below)

To use this functionality, ensure that the ScrollToTop component is included as a sibling to the BrowserRouter component. This setup allows the ScrollToTop component to receive the history object and respond to route changes accordingly. Ensure that you wrap your main component with BrowserRouter to ensure the proper functioning of the components.

Here’s an example of integrating it into your main component:

ScrollToTop.js

import React, { useEffect } from 'react';
const ScrollToTop = () => {
  useEffect(() => {
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }, []); // Empty dependency array to run only on mount

  return null; // This component doesn't render anything
};

App.js

import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import ScrollToTop from './ScrollToTop';

const App = () => {
  return (
    <Router>
      <ScrollToTop />
      <Switch>
        {/* Your application routes here */}
      </Switch>
    </Router>
  );
};

With this setup, every time the route changes, the ScrollToTop component will smoothly scroll the window to the top.

Solution 2: Using react-router v6+ ScrollRestoration component

If you’re using React Router v6 or later, there’s a built-in component that automatically handles this behavior. Simply include it within your Router component. Here’s an example of integrating it into your component:

import { ScrollRestoration } from "react-router-dom";
function RootRouteComponent() {
  return (
    
{/* ... */}
); }

For further details, you can refer to the official documentation here.

Solution 3: Utilizing react-scroll Library

While the previous approach utilized the built-in window.scrollTo method, you can also achieve smooth scrolling with a third-party library like react-scroll. Here’s how to adapt the ScrollIntoView component to leverage react-scroll:

import React, { useEffect } from 'react';
import { animateScroll as scroll } from 'react-scroll';
import { withRouter } from 'react-router';

const ScrollIntoView = ({ children, location }) => {
  useEffect(() => {
    if (location) { // Ensure location prop is available
      scroll.scrollToTop({
        duration: 500,
        smooth: 'easeInOutQuint',
      });
    }
  }, [location]); // Run effect when location prop changes

  return children;
};
export default withRouter(ScrollIntoView);

Support On Demand!

                                         
ReactJS