Skip to content
Advertisement

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)'

Advertisement

Answer

If I understand your question you want to render a route that handles multiple categories.

  1. Render a single path with a match parameter. This allows you to dynamically handle any category value.

    <Route path='/categories/:category' component={itemList} /> 
    
  2. Render a single route with a path array. This allows you to handle specifically allowed categories. This results in path={["/categories/cat1", "/categories/cat2", ... , "/categories/cat6"]}.

    <Route
      path={itemCategories.map(cat => `/categories/${cat}`)}
      component={itemList}
    />
    
  3. Render a single route with a path array and map in the regex. This results in path='/categories/(cat1|cat2|cat3|cat4|cat5|cat6)' as you were looking for.

    <Route
      path={`/categories/(${itemCategories.map((cat) => cat).join("|")})`}
      component={ItemList}
    />
    
  4. Render a route for each category. This allows you to handle specifically allowed categories but basically duplicates the Route component.

    {
      itemCategories.map(cat => (
        <Route key={cat} path={`/categories/${cat}`} component={itemList} />
      ))
    }
    

I want to route just for cat1 to cat6. If user types something else like categories/cat7 notFound page will appear.

For this I would suggest option 2 or 3.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement