Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React routing to a page with dynamically determined slug [duplicate]

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

  • From the page that displays a list of entries (each entry has a unique id and a slug that is known)
  • When you click on one entry you are taken to that entry's page
  • The page is loaded dynamically - an ajax request is sent with the page's id and all the content is filled based on the request's output.

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.

like image 716
foobar Avatar asked Mar 07 '23 15:03

foobar


1 Answers

You can do this:

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

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

like image 98
Max Avatar answered Apr 07 '23 00:04

Max