Juliano
Juliano

Reputation: 137

React Route dynamic urls with undetermined slashes

I have an array of object I'm looping it and displaying in component 1 with links to url-key:

[
{"id":1, "url-key":"hello/how/are/you"},
{"id":2, "url-key":"another/url"},
{"id":3, "url-key":"yet/another/url"}
]

in component 2:

const UserPage = ({ match, location }) => {
  return (
    <>
      <p>
         hello user page.
      </p>  
    </>
  );
};

I've found that if use in Router:

<Route exact path="/user/:url_key+" component={component2} />

the above router is fine except that can load anything after /user/blabla and it will display: hello user page. how can I match wiht the url in the array of objects ?

Thnkx

Upvotes: 0

Views: 640

Answers (2)

Prathap Reddy
Prathap Reddy

Reputation: 1749

You can do .map of the array as below in your component 1 to map all the array url-key values to component 2

<Routes>
  myArray.map(obj => <Route key={obj.id} exact path={obj["url-key"]} component={component2} />)
</Routes>

Upvotes: 1

Juliano
Juliano

Reputation: 137

Prathap Reddy answer didn't quite work for me but definitely helpful:

This is what worked for me:

...
<Router>
{myArray.map(obj=> {return (<Route key={obj.id} exact path={"/"+obj.url_key} component={component2} />)})}
<Router>
...

I had to add prop Key to Route as it was complaining ERROR: Warning: Each child in a list should have a unique "key" prop. map even thought all ID's are unique I've seen this happened in all array.maps in react.

Upvotes: 1

Related Questions