I'm building a site with react and react-router and I have two different type of routes, like in the example bellow:
<Route name="products" path="/:type/*" handler={ ProductList } />
<Route name="generic-template" path="/*" handler={ TemplatePage } />
So my products page needs the type parameter, which can be A, B or C and I want any link that I access to match my products route only if the type is A, B or C. So as an example:
But with what I have now, any page is matched by the Products route because the type is simply matched as the first string after the slash. As a workaround, I tried to wrap my ProductList component into separate wrapper components that just send that type parameter along like this:
var TypeAWrapper = React.createClass({
render: function () {
return (
<ProductList params={{ splat: this.props.params.splat, type: 'A' }} />
);
}
});
var TypeBWrapper = React.createClass({
render: function () {
return (
<ProductList params={{ splat: this.props.params.splat, type: 'B' }} />
);
}
});
and then I used a different route for each type of product with static matching.
Does anyone know a better solution for this?
The Route component from react-router is public by default but we can build upon it to make it restricted. We can add a restricted prop with a default value of false and use the condition if the user is authenticated and the route is restricted, then we redirect the user back to the Dashboard component.
To add in an optional path parameter in React Router, you just need to add a ? to the end of the parameter to signify that it is optional. And then in your component you could access the GET parameters using the location.search prop that is passed in by React Router.
Using componentDidUpdate method of React page lifecycle, you can handled or disabled go back functionality in browser. basically componentDidUpdate method will call automatocally when component got updated. so once your component is updated you can prevent to go back as below.
extracted from official documentation
{/* It's possible to use regular expressions to control what param values should be matched.
* "/order/asc" - matched
* "/order/desc" - matched
* "/order/foo" - not matched*/}
<Route
path="/order/:direction(asc|desc)"
component={ComponentWithRegex}
/>
You could mix regular expressions with the exact props of the Route component to avoid that product is always matched
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