<Scripts> component.
Type Declaration
Props
A function that returns a key to use for scroll restoration. This is useful for custom scroll restoration logic, such as using only the pathname so that later navigations to prior paths will restore the scroll.Defaults to
location.key.The key to use for storing scroll positions in
sessionStorage. Defaults to "react-router-scroll-positions".The nonce to use for the inline script tag. This is useful for Content Security Policy (CSP) compliance.
Examples
Basic Usage
Pathname-based Restoration
Conditional Restoration
With CSP Nonce
Preventing Scroll Reset
You can prevent scroll reset on individual navigations using thepreventScrollReset prop on <Link> or <Form>:
Behavior
- Saves scroll positions to
sessionStorageon navigation - Restores scroll positions on back/forward navigation
- Resets scroll to top on new navigations (push)
- Renders an inline
<script>to prevent scroll flashing - Script runs before React hydrates to restore scroll immediately
How It Works
- On mount and navigation, saves the current scroll position to
sessionStorage - On back/forward navigation, restores the scroll position from
sessionStorage - The inline script prevents scroll flashing by restoring scroll before React hydrates
- Uses
location.keyby default to uniquely identify each location in the history stack
Notes
- Only render one
<ScrollRestoration>per app - Should be rendered before
<Scripts>in the document - Works automatically with browser back/forward buttons
- Respects
preventScrollReseton<Link>and<Form>components - In SPA mode (no server rendering), returns
nullas there’s nothing to restore initially
Styling Considerations
If you’re using CSS selectors likenav :last-child, be aware that <ScrollRestoration> may render <link rel="prefetch"> tags after your navigation links. Use nav :last-of-type instead: