Skip to content
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
9 changes: 8 additions & 1 deletion packages/wouter/src/use-hash-location.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,11 @@ export const useHashLocation = ({ ssrPath = "/" } = {}) => [
navigate,
];

useHashLocation.hrefs = (href) => "#" + href;
// Search stays before the hash, matching `navigate`. A query inside the hash
// (`#/settings?tab=1`) is not a separate search and fails route matching.
useHashLocation.hrefs = (href) => {
const queryAt = href.indexOf("?");
return queryAt < 0
? "#" + href
: href.slice(queryAt) + "#" + href.slice(0, queryAt);
};
36 changes: 35 additions & 1 deletion packages/wouter/test/use-hash-location.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { test, expect, mock } from "bun:test";
import { renderHook, render, act, fireEvent } from "@testing-library/react";
import { renderToStaticMarkup } from "react-dom/server";

import { Router, Route, useLocation, Link } from "../src/index.js";
import { Router, Route, useLocation, useSearch, Link } from "../src/index.js";
import { useHashLocation } from "../src/use-hash-location.js";

import { waitForHashChangeEvent } from "./test-utils";
Expand Down Expand Up @@ -377,3 +377,37 @@ test("uses string URLs as hashchange event payload", () => {

removeEventListener("hashchange", hashChangeFn);
});

test("Link href keeps a query before the hash so opening it matches the route", () => {
history.replaceState(null, "", "/app#/home");

const { getByRole, unmount } = render(
<Router hook={useHashLocation}>
<Link href="/settings?tab=profile">Settings</Link>
</Router>
);

const href = getByRole("link", { name: "Settings" }).getAttribute("href");
expect(href).toBe("?tab=profile#/settings");
unmount();

const opened = new URL(href!, "https://example.test/app");
history.replaceState(null, "", opened.pathname + opened.search + opened.hash);

const Settings = () => {
const search = useSearch();
return <>Settings page {search}</>;
};

const { getByText, queryByText } = render(
<Router hook={useHashLocation}>
<Route path="/settings">
<Settings />
</Route>
<Route path="/home">Home</Route>
</Router>
);

expect(queryByText("Home")).not.toBeInTheDocument();
expect(getByText("Settings page tab=profile")).toBeInTheDocument();
});
Loading