'how can i use array in routing with react-router
This is my routing with regex pattern by react-router.
ItemList component appears when the URL is /categories/cat1 or /categories/cat2 or /categories/cat3 or /categories/cat4 or /categories/cat5 or /categories/cat6 otherwise NotFound component appears.
function App() {
return (
<Router>
<Header />
<Container >
<Switch>
<Route exact path='/' component={Home} />
<Route path='/categories/(cat1|cat2|cat3|cat4|cat5|cat6)' component={ItemList} />
<Route path="*" component={NotFound} />
</Switch>
</Container>
<Footer />
</Router>
);
}
I want to use dynamic array for ItemList routing like this:
const itemCategories = ['cat1','cat2','cat3','cat4','cat5','cat6'];
in this path:
path='/categories/(cat1|cat2|cat3|cat4|cat5|cat6)'
Solution 1:[1]
You can use : to set it to a dynamic route like this:
<Route path="/categories/:cat" component={itemList} />
and then render the route according to the users choice
Or you can map the routes like this:
{itemCategories.map(route => {
return <Route path=`/categories/${route}}` component={itemList}/>
}}
I'm not sure what you want so I gave both options
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
