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;
}}
/>
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
Contact Us