reactjsreduxreact-router

React routing to a page with dynamically determined slug


I am using React, Redux and React-router and would like to get the following use case to work:

How can I create a url with each item's slug? Right now I just have a fixed

<Route path="/item" component={ItemPage} />

What I would want is

<Route path="/<slug>" component={ItemPage} />

where slug is only known once you navigate to the page from another page.

Another issue I have - all content of the page disappears upon refresh. This is caused by the fact that I pass the item id to the ItemPage via state, and the the id is no longer set in the state after a refresh.

Maybe more generally, what would be the way to implement the above behaviour? It seems like a common use case and I can't find a good reference on how to do it.


Solution

  • You can do this:

    <Route path="/:slug" element={<ItemPage/>} />

    Check out this example from the react-router docs on URL params.