Path parameters
Edit this pageParameters within a route are used to capture dynamic values from the URL. This is useful for creating routes that are more flexible and can handle different values.
In this example, the :id
parameter will capture any value that comes after /users/
in the URL.
The colon :
is used to denote a parameter, and id
is the name of the parameter.
When a URL matches this route, the User
component will be rendered.
Routes that share the same path match will be treated as the same route.
If a force re-render is needed, you can wrap your component in a keyed Show
component:
Accessing parameters
You can retrieve the values captured by parameters using useParams
.
Validating parameters
Each path parameter can be validated using the MatchFilter
on the Route
component.
Rather than checking for the presence of a parameter manually, you can use a MatchFilter
to ensure that the parameter is in the correct format.
Here, the matchFilter
prop validates the parent
, id
, and withHtmlExtension
parameters against the specified filters defined in the filters
object.
If the validation fails, the route will not match and the component will not be rendered.
In this example, that means:
/users/mom/123/contact.html
would match,/users/dad/456/about.html
would match,/users/aunt/123/contact.html
would not match as:parent
is not 'mom' or 'dad',/users/mom/me/contact.html
would not match as:id
is not a number,/users/dad/123/contact
would not match as:withHtmlExtension
is missing .html.
Optional parameters
Parameters can be made optional by adding a ?
after the parameter name.
With this setup, the route would match both /users
and /users/123
.
However, it is important to note that the ?
only makes the parameter optional for the last segment of the path.
As a result, paths beyond the optional parameter will not be matched.
For instance, /users/123/contact
would not match.
Wildcard routes
Wildcard routes can be used to match any number of segments in a path.
To create a wildcard route, use *
followed by the parameter name.
Using an asterisk *
as a parameter will match any number of segments after /users
.
This includes /users
, /users/123
, /users/123/contact
, and so on.
If you need to expose the wildcard segments of the path, you can name them:
In this case, rest
will contain the rest of the path after /users/
.
It is important to note that wildcard routes must be located at the end of the path.
If you place a wildcard route before the end, such as /users/*rest/:id
, no routes will be matched.