What is ScrollRestoration in React Router

In React Router, scrollRestoration is a feature that helps maintain the scroll position of a webpage when navigating between different routes within a single-page application. When enabled, it ensures that when a user goes back or forward in their browsing history, the page remembers where they were scrolled to previously, rather than resetting to the top of the page.

This feature enhances the user experience by providing seamless navigation within the application without disrupting their reading or browsing flow. By default, the React Router does not handle scroll restoration. In this article, we’ll learn about ScrollRestoration in detail.

Table of Content

  • ScrollRestoration when user navigates to a different page
  • When user reloads the page
  • getKey Prop
  • Preventing Scroll Reset

Steps to Create a React App and Installing Module

Step 1: Create a React application by using the following command in the terminal.

npx create-react-app foldername

Step 2: Now, go to the project folder i.e. nesting-demo by running the following command.

cd foldername

Step 3: Let’s install the React Router DOM npm package required for this project

npm i react-router-dom

Project Structure:

The dependencies list in package.json file:

"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.16.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}

ScrollRestoration when user navigates to a different page

Scroll restoration maintains the scroll to a specific position when the user navigates to a different page within a single-page application. In this example the ScrollToBottom component is a React functional component responsible for scrolling the page to the bottom whenever the pathname (the current location’s pathname) changes. It utilizes React Router’s useLocation hook to access the current location. Inside the useEffect hook, it listens for changes to the pathname dependency. When a change occurs (i.e., when the user navigates to a different route), the window.scrollTo function is called with parameters (0, document.body.scrollHeight), which scrolls the window to the bottom of the page. This ensures that whenever the user navigates to a new page, they are automatically scrolled to the bottom, providing a smoother browsing experience. Finally, the component returns null as it doesn’t render any UI elements directly.

Example: In this example the page scrolls to bottom on restore

JavaScript
// App.js
import React from 'react'
import {
    BrowserRouter as Router,
    Routes,
    Route,
    Link
} from 'react-router-dom'
import Home from './Home'
import About from './About'
import ScrollToBottom from './ScrollToBottom'

const App = () => {
    return (
        <Router>
            <ScrollToBottom />
            <nav>
                <ul>
                    <li>
                        <Link to="/">Home</Link>
                    </li>
                    <li>
                        <Link to="/about">About</Link>
                    </li>
                </ul>
            </nav>
            <Routes>
                <Route path="/" element={<Home />} />
                <Route path="/about" element={<About />} />
            </Routes>
        </Router>
    )
}

export default App
JavaScript
// src/Home.js
import React from 'react';

const Home = () => {
    return (
        <div style={styles.homeContainer}>
            <h2 style={styles.heading}>w3wiki</h2>
            <p>Welcome to our homepage!</p>
            <p>Move to Aboutus to see more content.</p>
        </div>
    );
};

const styles = {
    homeContainer: {
        textAlign: 'center', // Center content horizontally
    },
    heading: {
        color: 'green', // Change heading color to green
    }
};

export default Home;
JavaScript
// src/About.js
import React from 'react';

const About = () => {
    return (
        <div>
            <h2>About w3wiki</h2>
            <h3>Company Profile and Brand:</h3>
            <p>
                w3wiki is a leading platform that provides computer
                science resources and coding challenges for programmers
                and technology enthusiasts, along with interview and exam
                preparations for upcoming aspirants. With a strong emphasis
                on enhancing coding skills and knowledge, it has become a
                trusted destination for over 12 million plus registered users
                worldwide. The platform offers a vast collection of tutorials,
                practice problems, interview tutorials, articles, and
                courses, covering various domains of computer science.
            </p>
            <p>
                Our exceptional mentors hailing from top colleges &
                organizations have the ability to guide you on a journey from
                the humble beginnings of coding to the pinnacle of expertise.
                Under their guidance watch your skills flourish as we lay
                the foundation and help you conquer the world of coding.
            </p>
            <p>
                Our brand is built on the pillars of expertise, accessibility,
                and community. We strive to empower individuals to enhance
                their programming skills, to bridge the gap between academia
                and industry, and provide a supportive community to the
                learners. w3wiki is committed to promoting technological
                advancement and providing opportunities for growth in the
                ever-evolving field of computer science.
            </p>

            <h3>Corporate History, Mission, Vision, and Motto:</h3>
            <h4>Corporate History:</h4>
            <p>
                w3wiki was founded in 2008 by Sandeep Jain with
                a vision to establish a comprehensive platform for computer
                science education and skill development. Over the years,
                the platform has experienced exponential growth,
                cementing its position as one of the most trusted
                and renowned names in the programming community.
            </p>

            <h4>Mission:</h4>
            <p>
                Our mission is to empower programmers and technology
                enthusiasts worldwide to excel in their coding skills
                and unleash their full potential. We want to bridge
                the gap between theory and practice, equipping individuals
                with skills and expertise required to tackle real-world
                challenges in the ever-evolving field of technology and
                get them prepared for their dream jobs.
            </p>

            <h4>Vision:</h4>
            <p>
                We envision a world where every programmer has unfettered
                access to top-tier learning resources, enabling them to
                continuously enhance their skills and flourish amidst
                the ever-evolving technology landscape. w3wiki
                aspires to be the definitive platform for programmers,
                empowering them to stay at the forefront of their
                careers and make a significant impact in the dynamic
                tech industry. With the time we have evolved and
                introduced other core fields preparation courses
                to support the young aspirants.
            </p>

            <h4>Motto:</h4>
            <p>
                Learn, Practice, and Excel  This motto encapsulates
                our unwavering dedication to continuous learning,
                hands-on practice, and the pursuit of excellence.
                We firmly believe that learning is an ongoing journey
                that spans a lifetime, and with persistent practice
                and unwavering dedication, individuals can truly
                excel in the vast realm of computer science.
            </p>

            <h3>Company Founders/Directors:</h3>
            <p>
                Our founder Sandeep Jain is a visionary entrepreneur
                and esteemed computer science expert. Fueled by his
                unwavering passion for coding and education, laid
                the very bedrock upon which w3wiki stands
                today, and his indomitable spirit has been instrumental
                in its remarkable growth and resounding success.
                As the steadfast driving force behind the company,
                Sandeep remains a beacon of guidance and inspiration,
                propelling the team to constantly challenging limits
                and craft transformative learning experiences.
            </p>
            <p>
                Our CTO, Shikhar Goel has an impeccable track record of
                developing revolutionary products, with their innovative
                solutions serving as a vital catalyst for the remarkable
                success of w3wiki. Shikhar, the mastermind behind
                the creation of this platform, has demonstrated a progressive
                approach and an unwavering commitment to excellence,
                propelling the company to become the premier destination
                for coding enthusiasts worldwide.
            </p>
        </div>
    );
};

export default About;
JavaScript
// ScrollToBottom.js
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';

const ScrollToBottom = () => {
  const { pathname } = useLocation();

  useEffect(() => {
    window.scrollTo(0, document.body.scrollHeight);
  }, [pathname]);

  return null;
};

export default ScrollToBottom;

Output:

When user reloads the page

When the user reloads the page, the browser resets the scroll position to the top by default. To maintain the scroll position upon page reload, you can use the beforeunload event to store the scroll position in the browser’s sessionStorage, and then retrieve and set it on page load.

Example: Below is an example when user reloads the page.

getKey Prop

The <ScrollRestoration> component with the getKey prop in React allows you to customize how scroll positions are tracked and restored when navigating between routes. The getKey prop is a function that determines the key used to identify each route. By default, it returns the location.key, which is a unique identifier for each route. This means that when you navigate between routes, React Router will track the scroll position separately for each route based on its key, ensuring that the scroll position is restored correctly when you return to a previously visited route.

Syntax:

<ScrollRestoration
getKey={(location, matches) => {
// default behavior
return location.key;
}}
/>

Preventing Scroll Reset

Preventing scroll reset in web applications involves ensuring that the scroll position of a page is maintained when the user interacts with the application. This is particularly important in scenarios where the page content dynamically changes, such as navigating between different pages or components. By default, certain actions like navigation or updating content can cause the browser to reset the scroll position to the top of the page. To prevent this, developers can implement techniques such as storing the scroll position before the change occurs and then restoring it afterward. This ensures a smoother and more seamless user experience, as users won’t lose their place when navigating or interacting with the application.

We can prevent the scroll to top behavior from our links and forms:

Syntax:

<Link preventScrollReset={true} />
<Form preventScrollReset={true} />


Contact Us