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

Fix useLocation to receive 0 instead of null when state is set to 0 #11495

Merged
merged 11 commits into from May 8, 2024
6 changes: 6 additions & 0 deletions .changeset/smooth-sloths-exist.md
@@ -0,0 +1,6 @@
---
"react-router-dom": patch
"react-router-dom-v5-compat": patch
---

Allow falsy `location.state` values passed to `<StaticRouter>`
1 change: 1 addition & 0 deletions contributors.yml
Expand Up @@ -253,3 +253,4 @@
- yracnet
- yuleicul
- zheng-chuang
- jungwoo3490
2 changes: 1 addition & 1 deletion packages/react-router-dom-v5-compat/lib/components.tsx
Expand Up @@ -86,7 +86,7 @@ export function StaticRouter({
pathname: locationProp.pathname || "/",
search: locationProp.search || "",
hash: locationProp.hash || "",
state: locationProp.state || null,
state: locationProp.state != null ? locationProp.state : null,
key: locationProp.key || "default",
};

Expand Down
26 changes: 26 additions & 0 deletions packages/react-router-dom/__tests__/static-location-test.tsx
Expand Up @@ -56,5 +56,31 @@ describe("A <StaticRouter>", () => {
key: expect.any(String),
});
});

it("retains a non-null state when passed explicitly", () => {
let location!: ReturnType<typeof useLocation>;
function LocationChecker() {
location = useLocation();
return null;
}

ReactDOMServer.renderToStaticMarkup(
<StaticRouter
location={{ pathname: "/the/path", search: "?the=query", state: 0 }}
>
<Routes>
<Route path="/the/path" element={<LocationChecker />} />
</Routes>
</StaticRouter>
);

expect(location).toEqual({
pathname: "/the/path",
search: "?the=query",
hash: "",
state: 0,
key: expect.any(String),
});
});
});
});
2 changes: 1 addition & 1 deletion packages/react-router-dom/server.tsx
Expand Up @@ -66,7 +66,7 @@ export function StaticRouter({
pathname: locationProp.pathname || "/",
search: locationProp.search || "",
hash: locationProp.hash || "",
state: locationProp.state || null,
state: locationProp.state != null ? locationProp.state : null,
key: locationProp.key || "default",
};

Expand Down