Reputation:
I am working with react-router for the first time.
Here is my piece of code.
<Switch>
<Route exact path="/" component={Home} />
<Route path="/A/xx/xxx/:feeros" component={About} />
<Route path="/B/xx/xxx/:feeros" component={About} />
<Route path="/C/xx/xxx/:feeros" component={About} />
<Route path="/D/xx/xxx/:feeros" component={About} />
</Switch>
This part of the <Route path="//xx/xxx/:feeros" component={About} />
code is always repeated.There is no way to reduce this react router ?
Upvotes: 13
Views: 457
Reputation: 6858
If you need to handle four specific routes (A | B | C | D);
<Route path="/(A|B|C|D)/xx/xxx/:feeros" component={About} />
If you still need to intercept the parameter, but the values can only be A | B | C | D, then you can write this:
<Route path="/:letter(A|B|C|D)/xx/xxx/:feeros" component={About} />
You will have two parameters:
const { letter, feeros } = match.params;
letter can only be: "A", "B", "C" or "D"
You can use another regular expression.
for example so:
<Route path="/([a-zA-Z])/xx/xxx/:feeros" component={About} />
The route will work for one Latin letter, for example:
'/A/xx/xxx/value'
'/s/xx/xxx/value'
'/F/xx/xxx/value'
Moreover, you can use regular expressions for parameters:
<Route path="/([a-zA-Z])/xx/xxx/:feeros(\d{2})" component={About} />
Matches routes with two-digit feeros values:
'/A/xx/xxx/11'
'/s/xx/xxx/21'
'/F/xx/xxx/45'
Upvotes: 12
Reputation: 4885
Use Route Params.
<Switch>
<Route exact path="/" component={Home} />
<Route path="/:letter/xx/xxx/:feeros" component={About} />
</Switch>
On the component side you can grab the parameter value:
componentDidMount() {
const { match: { params } } = this.props;
console.log(params.letter);
console.log(params.feeros);
}
Upvotes: 2
Reputation: 14199
you could have a paramter to identitfy: A
, B
, etc.
<Switch>
<Route exact path="/" component={Home} />
<Route path="/:id/xx/xxx/xx" component={About} />
</Switch>
Upvotes: 1