Reck
Reck

Reputation: 8762

How to validate url params with react-router?

I have a website that allows for urls of them form /widgets/:id. I have no more than 50 widgets, so /widgets/51 is not a valid url. How do I go about rendering an error page when id is bigger than 50?

Should I be validating the value of id in my Widget component? Or should I be validating it at the routes level? Also, I would prefer that the act of displaying an error page does not change the url. That is to say, if a user navigates to /widgets/51 I would like to display an error page, but I would like the url that gets displayed in the browser to keep reading /widgets/51.

Many thanks in advance!

Upvotes: 0

Views: 2021

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281606

If you prefer that the URL doesn't not change when you handle the error message then, you should be having the logic to test the params in the Widget component. You should do it as follows

render() {
    if(this.props.match.params.id > 50) {
        return <ErrorView/>
    }else {
        return <WidgetView/>
    }
}

Upvotes: 2

Related Questions