0

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

3 Answers 3

2

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} />
Sign up to request clarification or add additional context in comments.

1 Comment

I think this is best probably. In the / case it's going to default to current month anyway when those are undefined.
2

Try providing explicit parameters with regex:

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

Comments

1

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.

1 Comment

Thanks! New to react - but I was also wondering how to do that and then redirect on invalid ones. Based on the above google found me codementor.io/sahilmittal/… which looks like a good starting point

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.