Skip to content

Commit

Permalink
Make all params available to nested routes + parents (#7963)
Browse files Browse the repository at this point in the history
* feat: Make all params available to nested routes (#7960)

* add test case

* update type imports

* bump file size limits

Co-authored-by: Michael Jackson <michael@jackson.us>
  • Loading branch information
chaance and mjackson committed Aug 20, 2021
1 parent 7037663 commit 9de81d2
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 8 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,13 @@
"none": "6 kB"
},
"build/react-router/umd/react-router.production.min.js": {
"none": "7 kB"
"none": "8 kB"
},
"build/react-router-dom/react-router-dom.production.min.js": {
"none": "3 kB"
},
"build/react-router-dom/umd/react-router-dom.production.min.js": {
"none": "7 kB"
"none": "8 kB"
}
},
"prettier": {
Expand Down
29 changes: 29 additions & 0 deletions packages/react-router/__tests__/useParams-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -193,4 +193,33 @@ describe("useParams", () => {
);
});
});

describe("when the params match in a child route", () => {
it("renders params in the parent", () => {
let params: Record<string, string> = {};
function Blog() {
params = useParams();
return <h1>{params.slug}</h1>;
}

function BlogPost() {
return null;
}

createTestRenderer(
<Router initialEntries={["/blog/react-router"]}>
<Routes>
<Route path="/blog" element={<Blog />}>
<Route path=":slug" element={<BlogPost />} />
</Route>
</Routes>
</Router>
);

expect(typeof params).toBe("object");
expect(params).toMatchObject({
slug: "react-router"
});
});
});
});
12 changes: 6 additions & 6 deletions packages/react-router/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as React from "react";
import {
Action,
import { Action, createMemoryHistory, parsePath } from "history";
import type {
Blocker,
History,
InitialEntry,
Expand All @@ -10,9 +10,7 @@ import {
Path,
State,
To,
Transition,
createMemoryHistory,
parsePath
Transition
} from "history";

const readOnly: <T>(obj: T) => Readonly<T> = __DEV__
Expand Down Expand Up @@ -553,13 +551,15 @@ function useRoutes_(
}

// Otherwise render an element.
let allParams: Params = {};
let element = matches.reduceRight((outlet, { params, pathname, route }) => {
allParams = { ...allParams, ...params };
return (
<RouteContext.Provider
children={route.element}
value={{
outlet,
params: readOnly<Params>({ ...parentParams, ...params }),
params: readOnly<Params>({ ...parentParams, ...allParams }),
pathname: joinPaths([basenameForMatching, pathname]),
basename,
route
Expand Down

0 comments on commit 9de81d2

Please sign in to comment.