molefrog / wouter

🥢 A minimalist-friendly ~2.1KB routing for React and Preact
https://npm.im/wouter
The Unlicense
6.65k stars 152 forks source link

Allow using `RegExp` for paths alongside strings #449

Closed JonahPlusPlus closed 4 months ago

JonahPlusPlus commented 4 months ago

The regexparam library allows for passing RegExp through parse. I think it would be a useful feature to be able to use custom regular expressions for routes.

For example:

<Switch>
  <Route path="/:id">Hello</Route>
  <Route>404</Route>
</Switch>

id will match anything. But if we know that an ID will only be digits, it would be nice to use a regex to validate it:

const idRegex = /^[/](?<id>\d+)$/;

<Switch>
  <Route path={idRegex}>Hello</Route>
  <Route>404</Route>
</Switch>

If it doesn't match, it will continue on to the 404 page.

This uses a named capture group so it could be a direct drop in for "/:id".

Alternatively, a normal regex could be used:

/^[/](\d+)$/

// Then consumed like:
const params = useParams();
const id = params[1];

This allows for lifting validation out of routes. Patterns like route prefixes (/@:username) and multiple params in a single segment (/:id-:opt) becomes possible. And since it builds upon functionality that is already here, it won't cost much to implement.

molefrog commented 4 months ago

Released this in v3.2.0