Need to declare an optional path that contains a string and a parameter
Now I have this path
<Route exact path="/tasks/:id" render={(props) => (
<AsyncTask {...props} profile={this.state.profile} />
)} />
I need to have
/tasks/:id/notification/:notificationId
Where notification/:notificationId
is optional
I tried to add it this way, but it does not work
/tasks/:id/(notification/:notificationId)?
I need this to know if I am coming from a notification link, to mark it as read.
This is working
/tasks/:id/(notification)?/:notificationId?
But it matches and paths without notificationId
Sadly there doesn't seem to be a way to do this. The ideal way would be to create two separate Routes for your purpose.
<Route exact path="/tasks/:id" component={...} />
<Route exact path="/tasks/:id/notification/:notificationId" component={...} />
If you really must only declare one Route, you could use a custom regex rule (the part that is wrapped in parentheses after the parameter name declaration):
<Route exact path="/tasks/:id/:notificationId(notification/\d+)?" component={...} />
However!! - note that the notificationId
parameter will include the substring "notification"
. For example, if you have:
tasks/123/notification/456
You will have a taskId
of "123"
and notificationId
of "notification/456"
(the whole string)!
That said, the route above will match the following paths:
tasks/123
tasks/123/notification/456
but not:
tasks/123/notification
tasks/123/notification/abc
tasks/123/456
etc...
TL;DR - You probably want to use two individual routes as shown in the first example above.
It looks like there isn't any support for this in React Router [1]. Maybe you could just use a query parameter instead? /tasks/:id?notification=notificationID
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With