Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using match in react routes

Within my <Switch /> I dynamically create routes with a dynamic path in which ideally will all load the same component.

I have a JSON object like so:

{
  "products": [{"name": "car"}]
}

Which just contains an array of products which currently only has one product with the name "car".

In the <Switch /> I loop through the products to create a route like so:

{
  ProductHelper.getAllProductPages().forEach(product => {
          console.log(product.name);
          return (
            <Route path={'/' + product.name + '/:id' } component={Search} />
          );
  })
};

The console log prints out "car" perfectly so i see no issue with getting the product name. However, when I navigate to /car/test I'd expect this to load the Search component but it doesn't.

When I create a route like this:

<Route path='/car/test' component={Search} />

This loads the Search component perfectly to prove that the component doesn't issues.

I really don't understand what im doing wrong here, does anyone have any idea?

like image 876
KTOV Avatar asked Apr 27 '26 13:04

KTOV


1 Answers

Instead of .forEach you should use .map, because forEach doesn't return an array. Map does

like image 185
Alexei Crecotun Avatar answered Apr 30 '26 03:04

Alexei Crecotun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!