Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add behavior prop to <ScrollRestoration /> #11701

Open
wants to merge 3 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/little-snails-hide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"react-router-dom": minor
---

Add `behavior` prop to `<ScrollRestoration />`
1 change: 1 addition & 0 deletions contributors.yml
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@
- gowthamvbhat
- GraxMonzo
- GuptaSiddhant
- h3rmanj
- haivuw
- hernanif1
- holynewbie
Expand Down
11 changes: 11 additions & 0 deletions docs/components/scroll-restoration.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,16 @@ Or you may want to only use the pathname for some paths, and use the normal beha
/>
```

## `behavior`

Optional prop that specifies which scroll behavior to use when scrolling to a position.

Possible values: `smooth`, `instant`, `auto`.

Can be useful if you've set `scroll-behavior` globally, but want `<ScrollRestoration />` to use another behavior.

See also: [`scrollTo` behavior option][scroll-behavior]

## Preventing Scroll Reset

When navigation creates new scroll keys, the scroll position is reset to the top of the page. You can prevent the "scroll to top" behavior from your links and forms:
Expand All @@ -102,3 +112,4 @@ Server Rendering frameworks can prevent scroll flashing because they can send a
[preventscrollreset]: ../components/link#preventscrollreset
[form-preventscrollreset]: ../components/form#preventscrollreset
[pickingarouter]: ../routers/picking-a-router
[scroll-behavior]: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTo#behavior
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@
"none": "17.3 kB"
},
"packages/react-router-dom/dist/react-router-dom.production.min.js": {
"none": "17.2 kB"
"none": "17.3 kB"
},
"packages/react-router-dom/dist/umd/react-router-dom.production.min.js": {
"none": "23.6 kB"
Expand Down
84 changes: 75 additions & 9 deletions packages/react-router-dom/__tests__/scroll-restoration-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,9 @@ describe(`ScrollRestoration`, () => {

// check scroll activity
expect(mockScroll.mock.calls).toEqual([
[0, 0],
[0, 0],
[0, 100], // restored
[{ left: 0, top: 0, behavior: undefined }],
[{ left: 0, top: 0, behavior: undefined }],
[{ left: 0, top: 100, behavior: undefined }], // restored
]);

expect(consoleWarnMock).not.toHaveBeenCalled();
Expand Down Expand Up @@ -131,9 +131,11 @@ describe(`ScrollRestoration`, () => {
const mockScroll = jest.fn();
window.scrollTo = mockScroll;

jest.spyOn(window, "sessionStorage", "get").mockImplementation(() => {
throw new Error("denied");
});
const sessionStorageMock = jest
.spyOn(window, "sessionStorage", "get")
.mockImplementation(() => {
throw new Error("denied");
});

let router = createBrowserRouter(
[
Expand Down Expand Up @@ -174,9 +176,9 @@ describe(`ScrollRestoration`, () => {

// check scroll activity
expect(mockScroll.mock.calls).toEqual([
[0, 0],
[0, 0],
[0, 100], // restored (still possible because the user hasn't left the page)
[{ left: 0, top: 0, behavior: undefined }],
[{ left: 0, top: 0, behavior: undefined }],
[{ left: 0, top: 100, behavior: undefined }], // restored (still possible because the user hasn't left the page)
]);

expect(consoleWarnMock).toHaveBeenCalledWith(
Expand All @@ -186,7 +188,71 @@ describe(`ScrollRestoration`, () => {
);

consoleWarnMock.mockRestore();
sessionStorageMock.mockRestore();
});

it.each([undefined, "smooth", "instant", "auto"])(
"scrolls with the specified behavior",
(behavior) => {
const consoleWarnMock = jest
.spyOn(console, "warn")
.mockImplementation(() => {});

let testWindow = getWindowImpl("/base");
const mockScroll = jest.fn();
window.scrollTo = mockScroll;

let router = createBrowserRouter(
[
{
path: "/",
Component() {
return (
<>
<Outlet />
<ScrollRestoration
behavior={behavior}
getKey={(location) =>
"test3-" + behavior + location.pathname
}
/>
</>
);
},
children: testPages,
},
],
{ basename: "/base", window: testWindow }
);
let { container } = render(<RouterProvider router={router} />);

expect(getHtml(container)).toMatch("On page 1");

// simulate scrolling
Object.defineProperty(window, "scrollY", { writable: true, value: 100 });

// leave page
window.dispatchEvent(new Event("pagehide"));
fireEvent.click(screen.getByText("Go to page 2"));
expect(getHtml(container)).toMatch("On page 2");

// return to page
window.dispatchEvent(new Event("pagehide"));
fireEvent.click(screen.getByText("Go to page 1"));

expect(getHtml(container)).toMatch("On page 1");

// check scroll activity
expect(mockScroll.mock.calls).toEqual([
[{ left: 0, top: 0, behavior }],
[{ left: 0, top: 0, behavior }],
[{ left: 0, top: 100, behavior }],
]);

expect(consoleWarnMock).not.toHaveBeenCalled();
consoleWarnMock.mockRestore();
}
);
});

const testPages = [
Expand Down
12 changes: 8 additions & 4 deletions packages/react-router-dom/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1330,6 +1330,7 @@ if (__DEV__) {
export interface ScrollRestorationProps {
getKey?: GetScrollRestorationKeyFunction;
storageKey?: string;
behavior?: ScrollBehavior;
}

/**
Expand All @@ -1339,8 +1340,9 @@ export interface ScrollRestorationProps {
export function ScrollRestoration({
getKey,
storageKey,
behavior,
}: ScrollRestorationProps) {
useScrollRestoration({ getKey, storageKey });
useScrollRestoration({ getKey, storageKey, behavior });
return null;
}

Expand Down Expand Up @@ -1780,9 +1782,11 @@ let savedScrollPositions: Record<string, number> = {};
function useScrollRestoration({
getKey,
storageKey,
behavior,
}: {
getKey?: GetScrollRestorationKeyFunction;
storageKey?: string;
behavior?: ScrollBehavior;
} = {}) {
let { router } = useDataRouterContext(DataRouterHook.UseScrollRestoration);
let { restoreScrollPosition, preventScrollReset } = useDataRouterState(
Expand Down Expand Up @@ -1874,7 +1878,7 @@ function useScrollRestoration({

// been here before, scroll to it
if (typeof restoreScrollPosition === "number") {
window.scrollTo(0, restoreScrollPosition);
window.scrollTo({ left: 0, top: restoreScrollPosition, behavior });
return;
}

Expand All @@ -1895,8 +1899,8 @@ function useScrollRestoration({
}

// otherwise go to the top on new locations
window.scrollTo(0, 0);
}, [location, restoreScrollPosition, preventScrollReset]);
window.scrollTo({ left: 0, top: 0, behavior });
}, [location, restoreScrollPosition, preventScrollReset, behavior]);
}
}

Expand Down