MrPurpleStreak
MrPurpleStreak

Reputation: 1557

Can react router have a route with multiple option parameters where (e.g.) both are required, or none

Using react-router-dom I have a route like so:

<Route path='/:year?/:month?' component={ThingUsingYearAndMonth} />

But really I want BOTH year and month to exist (e.g. /2018/Dec or /2017/Jan) or neither. I.e. just /2018 wouldn't match

Upvotes: 0

Views: 138

Answers (3)

Pranay Tripathi
Pranay Tripathi

Reputation: 1882

I don't think there is any mechanism provided by the react-router-dom to validate the route params. You are better off creating your own Higher Order Component and validate the route params in it. Or you can use regex to validate your params in the route itself.

Upvotes: 1

Blue
Blue

Reputation: 22911

Try providing explicit parameters with regex:

<Route path='/:year(\\d{4})?/:month([A-Za-z]+)?' component={ThingUsingYearAndMonth} />

Upvotes: 2

Ryan Cogswell
Ryan Cogswell

Reputation: 81006

I would probably handle that using two routes -- one for when both are provided and one for when neither are provided:

<Route path='/:year/:month' component={ThingUsingYearAndMonth} />
<Route path='/' exact component={ThingUsingYearAndMonth} />

Upvotes: 2

Related Questions