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

Added location param override to Routes #7969

Merged
merged 1 commit into from
Sep 1, 2021
Merged
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
72 changes: 72 additions & 0 deletions packages/react-router/__tests__/Routes-location-test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import * as React from "react";
import { create as createTestRenderer } from "react-test-renderer";
import {
MemoryRouter as Router,
Route,
Routes,
useParams
} from "react-router";

describe("<Routes> with a location", () => {

function Home() {
return <h1>Home</h1>;
}

function User() {
let { userId } = useParams();
return (
<div>
<h1>User: {userId}</h1>
</div>
);
}

it("matches when the location is overridden", () => {

const location = {
pathname: '/home',
search: '',
hash: '',
state: null,
key: 'r9qntrej'
};
const renderer = createTestRenderer(
<Router initialEntries={["/users/michael"]}>
<Routes location={location}>
<Route path="home" element={<Home />} />
<Route path="users/:userId" element={<User />} />
</Routes>
</Router>
);

expect(renderer.toJSON()).not.toBeNull();
expect(renderer.toJSON()).toMatchInlineSnapshot(`
<h1>
Home
</h1>
`);
});


it("matches when the location is not overridden", () => {
const renderer = createTestRenderer(
<Router initialEntries={["/users/michael"]}>
<Routes>
<Route path="home" element={<Home />} />
<Route path="users/:userId" element={<User />} />
</Routes>
</Router>
);

expect(renderer.toJSON()).not.toBeNull();
expect(renderer.toJSON()).toMatchInlineSnapshot(`
<div>
<h1>
User:
michael
</h1>
</div>
`);
});
});
8 changes: 5 additions & 3 deletions packages/react-router/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,7 @@ export function Router({
export interface RoutesProps {
basename?: string;
children?: React.ReactNode;
location?: Location;
}

/**
Expand All @@ -265,11 +266,12 @@ export interface RoutesProps {
*/
export function Routes({
basename = "",
children
children,
location
}: RoutesProps): React.ReactElement | null {
let routes = createRoutesFromChildren(children);
let location = useLocation();
return useRoutes_(routes, location, basename);
let location_ = useLocation();
return useRoutes_(routes, location ?? location_, basename);
}

///////////////////////////////////////////////////////////////////////////////
Expand Down