13

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

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I will go with 2 routes, or using query params as @Matt mentioned above. Thx for answer. Regex way is also a good idea.
@AndrewLuca, yes; it adds some flexibility.
In case someone is wondering, this does not remount the component, so it's really ok to define 2 routes for the same component.
2

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.

1 Comment

It makes sense, because this type of URL is temporary. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.