1

I want to get and display individual param from multiple params in react-router-dom like in this URL http://localhost/tag/news/local/tour. The URL has three params which is the last two are optional.

Here are routes and components:

// routes.js
<Switch>
    <Route exact path="/" component={Home} />
    <Route path="/tag/:slug/:slug1?/:slug2?" component={Archives} />
    <Route path="*" component={ErrorPage} />
</Switch>

// Component: RenderTags.js
const RenderTags = props => {

  console.log(props.match.params) // output ==> Object{slug: "news", slug1: "local", slug2: "tour"}

  let taglists = '';

  if(props.match.params.slug1 !== undefined) {
    taglists = props.match.params.slug1
  } else if(props.match.params.slug2 !== undefined) {
    taglists = props.match.params.slug2
  } else {
    taglists = taglists = props.match.params.slug
  }

  return (
    <div>
      <h1>Tags</h1>
      Tag Slug: {taglists}
    </div>
  )
}

However, it works only at first and second, not the third. For example, if I access that full URL, I got this Tag Slug: local instead of Tag Slug: tour.

How to fix it? Any help will be much appreciated.

Note: I've used a simple way (may be for last alternatives) with props.match.url.split('/').pop() and it works, but I am still curious if there was a different approach related to my question.

Regards

mrale81
  • 77
  • 1
  • 9

0 Answers0