Skip to content

Commit

Permalink
Convenient no-path Route trick.
Browse files Browse the repository at this point in the history
  • Loading branch information
molefrog committed Feb 4, 2024
1 parent 31052d5 commit a83bab7
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 4 deletions.
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,15 @@ import { Route } from "wouter";
<Route path="/orders/:status" component={Orders} />
```

A route with no path is considered to always match, and it is the same as `<Route path="*" />`. When developing your app, use this trick to peek at the route's content without navigation.

```diff
-<Route path="/some/page">
+<Route>
{/* Strip out the `path` to make this visible */}
</Route>
```

#### Route Nesting

Nesting is a core feature of wouter and can be enabled on a route via the `nest` prop. When this prop is present, the route matches everything that starts with a given pattern and it creates a nested routing context. All child routes will receive location relative to that pattern.
Expand Down
5 changes: 1 addition & 4 deletions packages/wouter/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,14 +77,11 @@ export const useSearch = () => {
};

const matchRoute = (parser, route, path, loose) => {
// falsy patterns mean this route "always matches"
if (!route) return [true, {}];

// when parser is in "loose" mode, `$base` is equal to the
// first part of the route that matches the pattern
// (e.g. for pattern `/a/:b` and path `/a/1/2/3` the `$base` is `a/1`)
// we use this for route nesting
const { pattern, keys } = parser(route, loose);
const { pattern, keys } = parser(route || "*", loose);
const [$base, ...matches] = pattern.exec(path) || [];

return $base !== undefined
Expand Down
12 changes: 12 additions & 0 deletions packages/wouter/test/use-params.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,18 @@ it("returns empty object when used outside of <Route />", () => {
expect(result.current).toEqual({});
});

it("contains a * parameter when used inside an empty <Route />", () => {
const { result } = renderHook(() => useParams(), {
wrapper: (props) => (
<Router hook={memoryLocation({ path: "/app-2/goods/tees" }).hook}>
<Route>{props.children}</Route>
</Router>
),
});

expect(result.current).toEqual({ "*": "app-2/goods/tees" });
});

it("returns an empty object when there are no params", () => {
const { result } = renderHook(() => useParams(), {
wrapper: (props) => <Route path="/">{props.children}</Route>,
Expand Down

0 comments on commit a83bab7

Please sign in to comment.