1

I have created a blogging App in react JS and would like to change the URL path when navigating to a blog article. However, I am running into a problem when using '/:id' in Route with React Router Dom.

Example when navigating to these two URLs:

Blog article URL:
https://website.com/myfirstblogpost/4582819

Profile page URL:
https://website.com/profile/902310

App.js setup

<Route path="/:id/:id" component={BlogArticle} exact={true} />
<Route path="/profile/:id" component={Profile} exact={true}/>

With this setup, my blog article is being shown on both the blog article route AND profile route. How do I fix this problem? Is it possible to do render a route like:

<Route path=`{/${blog.title}/${blog.id}}` component={BlogArticle} exact={true} />
<Route path=`{/profile/${user.id}`component={Profile} exact={true}/>

If so how if not what other solutions are there? Please note that due to SEO reasons the blog article title must be shown directly after the first '/' e.g. website.com/blogarticle

Many thanks guys!

Kind regards,

Frido

1 Answers1

2

There are two changes you need to do:

First: As the "profile" is hard-coded, you need to swap the order and put it in first position:

<Route path="/profile/:id" component={Profile} exact={true}/>
<Route path="/:id/:id" component={BlogArticle} exact={true} />

This way, React Router will first search for those "hard-coded" URLs, and then check the variable ones.

Second: You can't have two equal arguments on your URL if they are different (First is a string, probably a slug. Second is an integer). So you will need to modify it as:

<Route path="/profile/:id" component={Profile} exact={true}/>
<Route path="/:title/:id" component={BlogArticle} exact={true} />

This may do the trick!

Guilherme Toti
  • 574
  • 2
  • 7