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

Allow using RegExp for paths alongside strings #449

Closed
JonahPlusPlus opened this issue May 28, 2024 · 1 comment · Fixed by #450
Closed

Allow using RegExp for paths alongside strings #449

JonahPlusPlus opened this issue May 28, 2024 · 1 comment · Fixed by #450

Comments

@JonahPlusPlus
Copy link
Contributor

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
Copy link
Owner

Released this in v3.2.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants