Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set type of params in react-router

How to pass params in URL matching type?

For example I have /profile/:id which allows me to go /profile/1.

But problem is I can also go by /profile/1qwr/ and I'll get nothing.

How to check the type of the URL parameter and show error or something else?

like image 934
Андрей Гузюк Avatar asked Mar 05 '17 14:03

Андрей Гузюк


2 Answers

Note: This answer is outdated since v6: See discussion on Github (thanks to @dan for pointing this out).


Original answer:

Best solution, in my opinion, is to set a type on the id parameter by writing a simple regular expression.

If you want the id to accept only integers, this is what you'll do:

/profile/:id(\\d+)

/* the `(\\d+)` is a regular expression that will only accept integers */

Read more about this in path-to-regex documentation. path-to-regex is used by react-router internally, so there's no need to install anything.

like image 102
xyres Avatar answered Nov 08 '22 03:11

xyres


A. You cannot set type checking on params of the route.

B. If you want to show some error - handle it in your render method by getting the param like this this.props.params.id. But even here you cannot differentiate between the type because you will always get the string.

You can try using parseInt and check if the conversion is successful or not and determine then what to do.

like image 44
Arshabh Agarwal Avatar answered Nov 08 '22 03:11

Arshabh Agarwal