Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router 4 with optional path AND optional parameter

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

like image 800
iamandrewluca Avatar asked Oct 09 '17 13:10

iamandrewluca


2 Answers

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.

like image 99
Chris Avatar answered Sep 19 '22 22:09

Chris


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.

like image 22
Matt Avatar answered Sep 21 '22 22:09

Matt