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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With