Skip to content

Commit

Permalink
useRoutes should be able to return null when passing locationArg (
Browse files Browse the repository at this point in the history
#9485)

* useRoutes should be able to return `null` when passing `locationArg`

* Add danielberndt to contributors.yml

* add test cases to ensure that `useRoutes` returns `null` if no route matches
  • Loading branch information
danielberndt committed Oct 25, 2022
1 parent 2699759 commit 096edeb
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 1 deletion.
1 change: 1 addition & 0 deletions contributors.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
- codeape2
- coryhouse
- cvbuelow
- danielberndt
- dauletbaev
- david-crespo
- dokeet
Expand Down
51 changes: 51 additions & 0 deletions packages/react-router/__tests__/useRoutes-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,57 @@ describe("useRoutes", () => {
`);
});

it("returns null when no route matches", () => {
let routes = [{ path: "one", element: <h1>one</h1> }];

const NullRenderer = (props: { routes: RouteObject[] }) => {
const element = useRoutes(props.routes);
return element === null ? <div>is null</div> : <div>is not null</div>;
};

let renderer: TestRenderer.ReactTestRenderer;
TestRenderer.act(() => {
renderer = TestRenderer.create(
<MemoryRouter initialEntries={["/two"]}>
<NullRenderer routes={routes} />
</MemoryRouter>
);
});

expect(renderer.toJSON()).toMatchInlineSnapshot(`
<div>
is null
</div>
`);
});

it("returns null when no route matches and a `location` prop is passed", () => {
let routes = [{ path: "one", element: <h1>one</h1> }];

const NullRenderer = (props: {
routes: RouteObject[];
location?: Partial<Location> & { pathname: string };
}) => {
const element = useRoutes(props.routes, props.location);
return element === null ? <div>is null</div> : <div>is not null</div>;
};

let renderer: TestRenderer.ReactTestRenderer;
TestRenderer.act(() => {
renderer = TestRenderer.create(
<MemoryRouter initialEntries={["/two"]}>
<NullRenderer routes={routes} location={{ pathname: "/three" }} />
</MemoryRouter>
);
});

expect(renderer.toJSON()).toMatchInlineSnapshot(`
<div>
is null
</div>
`);
});

describe("warns", () => {
let consoleWarn: jest.SpyInstance;
beforeEach(() => {
Expand Down
2 changes: 1 addition & 1 deletion packages/react-router/lib/hooks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,7 @@ export function useRoutes(
// When a user passes in a `locationArg`, the associated routes need to
// be wrapped in a new `LocationContext.Provider` in order for `useLocation`
// to use the scoped location instead of the global location.
if (locationArg) {
if (locationArg && renderedMatches) {
return (
<LocationContext.Provider
value={{
Expand Down

0 comments on commit 096edeb

Please sign in to comment.