React Router scroll management functionality for Gatsby sites that preserves scroll positions during route navigation.
npx @tessl/cli install tessl/npm-gatsby-react-router-scroll@6.15.0React Router scroll management functionality for Gatsby sites that preserves scroll positions during route navigation. This package provides components and hooks to handle scroll restoration when navigating between pages, maintaining the user's scroll position when returning to previously visited pages.
npm install gatsby-react-router-scrollimport { ScrollContext, useScrollRestoration } from "gatsby-react-router-scroll";For CommonJS:
const { ScrollContext, useScrollRestoration } = require("gatsby-react-router-scroll");import React from "react";
import { ScrollContext, useScrollRestoration } from "gatsby-react-router-scroll";
// Using ScrollContext (ScrollHandler) for page-level scroll management
function App({ children, location, shouldUpdateScroll }) {
return (
<ScrollContext location={location} shouldUpdateScroll={shouldUpdateScroll}>
{children}
</ScrollContext>
);
}
// Using useScrollRestoration for custom element scroll restoration
function ScrollableList() {
const { ref, onScroll } = useScrollRestoration<HTMLDivElement>("my-list");
return (
<div
ref={ref}
onScroll={onScroll}
style={{ height: "400px", overflow: "auto" }}
>
{/* List content */}
</div>
);
}The package is built around two main components:
Provides a React context and component for managing scroll positions during navigation. Automatically saves and restores scroll positions when users navigate between pages.
export class ScrollHandler extends React.Component<
LocationContext & { shouldUpdateScroll: ShouldUpdateScroll }
>;
export const ScrollContext: React.Context<SessionStorage>;
type ShouldUpdateScrollFn = (
prevRouterProps: LocationContext | undefined,
routerProps: LocationContext
) => boolean;
type ShouldUpdateScroll = undefined | ShouldUpdateScrollFn;Hook for managing scroll positions of custom scrollable elements within pages.
function useScrollRestoration<T extends HTMLElement>(
identifier: string
): IScrollRestorationProps<T>;
interface IScrollRestorationProps<T extends HTMLElement> {
ref: MutableRefObject<T | null>;
onScroll(): void;
}interface LocationContext {
location: {
pathname: string;
search: string;
hash: string;
state?: any;
key?: string;
};
}
class SessionStorage {
read(location: Path, key: string): number;
save(location: Path, key: string, value: number): void;
getStateKey(location: Path, key: string): string;
}