diff --git a/integration/vite-spa-mode-test.ts b/integration/vite-spa-mode-test.ts index 12f9ebbcde..7dd1b168bb 100644 --- a/integration/vite-spa-mode-test.ts +++ b/integration/vite-spa-mode-test.ts @@ -1365,4 +1365,125 @@ test.describe("SPA Mode", () => { "app/routes/about.tsx", ]); }); + + test("hydrates NavLink active state for a deep link", async ({ page }) => { + let fixture = await createFixture({ + spaMode: true, + files: { + "app/root.tsx": js` + import { lazy, Suspense, useEffect, useState } from "react"; + import { Outlet, Scripts, useSearchParams } from "react-router"; + + const Menu = lazy(() => import("./layout-menu")); + + export function Layout({ children }: { children: React.ReactNode }) { + let [searchParams] = useSearchParams(); + let [initialTab] = useState(() => searchParams.get("tab") ?? ""); + useEffect(() => { + document.body.dataset.initialTab = initialTab; + }, [initialTab]); + + return ( + + + + + + + + + + {children} + + + + ); + } + + export default function App() { + return ; + } + `, + "app/layout-menu.tsx": js` + import { NavLink } from "react-router"; + + export default function Menu() { + return ( + + ); + } + `, + "app/routes/_index.tsx": js` + export default function Index() { + return

Home page

; + } + `, + "app/routes/other.tsx": js` + export default function Other() { + return

Other page

; + } + `, + }, + }); + let appFixture = await createAppFixture(fixture); + let releaseMenu!: () => void; + let menuReady = new Promise((resolve) => { + releaseMenu = resolve; + }); + + try { + await page.route("**/assets/layout-menu-*.js", async (route) => { + await menuReady; + await route.continue(); + }); + let html = await (await fixture.requestDocument("/")).text(); + let anchors = html.match(/]*>/g) ?? []; + expect(anchors).toHaveLength(2); + for (let anchor of anchors) { + expect(anchor).not.toMatch(/\bactive\b|aria-current=/); + } + + let app = new PlaywrightFixture(appFixture, page); + await Promise.all([ + page.waitForRequest("**/assets/layout-menu-*.js"), + app.goto("/other?tab=details", false), + ]); + await expect(page.locator("body")).toHaveAttribute( + "data-initial-tab", + "details", + ); + await expect(page.locator("nav a")).toHaveCount(2); + await expect(page.locator("nav a.active")).toHaveCount(0); + await expect(page.locator("nav a[aria-current]")).toHaveCount(0); + let otherLink = page.locator('a[href="/other"]'); + let prerenderedOtherLink = await otherLink.evaluateHandle((link) => link); + releaseMenu(); + await expect(page.locator("h1")).toHaveText("Other page"); + await expect(page.locator('a[href="/"]')).not.toHaveClass(/\bactive\b/); + await expect(otherLink).toHaveClass(/\bactive\b/); + await expect(otherLink).toHaveAttribute("aria-current", "page"); + expect( + await otherLink.evaluate( + (link, original) => link === original, + prerenderedOtherLink, + ), + ).toBe(true); + await expect(page.locator("nav a[aria-current]")).toHaveCount(1); + + await app.clickLink("/"); + await expect(page.locator("h1")).toHaveText("Home page"); + await expect(page.locator("body")).toHaveAttribute( + "data-initial-tab", + "details", + ); + await expect(page.locator('a[href="/"]')).toHaveClass(/\bactive\b/); + await expect(otherLink).not.toHaveClass(/\bactive\b/); + } finally { + releaseMenu(); + appFixture.close(); + } + }); }); diff --git a/packages/react-router/.changes/patch.spa-navlink-hydration.md b/packages/react-router/.changes/patch.spa-navlink-hydration.md new file mode 100644 index 0000000000..05ba78dc5b --- /dev/null +++ b/packages/react-router/.changes/patch.spa-navlink-hydration.md @@ -0,0 +1 @@ +Keep `NavLink` inactive in the prerendered Framework SPA fallback and set its active state from the browser URL after hydration diff --git a/packages/react-router/lib/dom/lib.tsx b/packages/react-router/lib/dom/lib.tsx index f3d4f46792..27c91508ff 100644 --- a/packages/react-router/lib/dom/lib.tsx +++ b/packages/react-router/lib/dom/lib.tsx @@ -1586,6 +1586,9 @@ export interface NavLinkProps extends Omit< | ((props: NavLinkRenderProps) => React.CSSProperties | undefined); } +const subscribeToNothing = () => () => {}; +const getClientSpaFallback = () => false; + /** * Wraps {@link Link | ``} with additional props for styling active and * pending states. @@ -1648,12 +1651,23 @@ export const NavLink = React.forwardRef( let location = useLocation(); let routerNavigation = React.useContext(DataRouterNavigationContext); let { navigator, basename } = React.useContext(NavigationContext); + let isSpaMode = React.useContext(FrameworkContext)?.isSpaMode === true; + + // SPA fallback HTML is reused across URLs. Keep the link state neutral + // until this link hydrates, including links inside a Suspense boundary. + let isSpaFallback = React.useSyncExternalStore( + subscribeToNothing, + getClientSpaFallback, + () => isSpaMode, + ); + let isTransitioning = routerNavigation != null && // Conditional usage is OK here because the usage of a data router is static // eslint-disable-next-line react-hooks/rules-of-hooks useViewTransitionState(path) && - viewTransition === true; + viewTransition === true && + !isSpaFallback; let toPathname = navigator.encodeLocation ? navigator.encodeLocation(path).pathname @@ -1686,12 +1700,14 @@ export const NavLink = React.forwardRef( ? toPathname.length - 1 : toPathname.length; let isActive = - locationPathname === toPathname || - (!end && - locationPathname.startsWith(toPathname) && - locationPathname.charAt(endSlashPosition) === "/"); + !isSpaFallback && + (locationPathname === toPathname || + (!end && + locationPathname.startsWith(toPathname) && + locationPathname.charAt(endSlashPosition) === "/")); let isPending = + !isSpaFallback && nextLocationPathname != null && (nextLocationPathname === toPathname || (!end &&