Tomek Buszewski
Tomek Buszewski

Reputation: 7955

React Router - one of two routes

I know the title may be vague, so I'll try to describe my problem as good as I can.

I am doing a WordPress theme and I need to link to both categories and tags pages. Their structure is /[categories|tags]/item. Now I need to make a route for those two items only. I tried doing it like this:

  <Route path="/category/:slug" component={Archives} />
  <Route path="/tag/:slug" component={Archives} />

But with this I have no distinction of wether this is a category or a tag. I dont wan't to go with <Route path="/:type/:slug" component={Archives} /> because this may get confusing when I'll need to use nested pages. I also don't want to change the url scheme.

Upvotes: 0

Views: 245

Answers (1)

deowk
deowk

Reputation: 4318

You can use queries to determine what the type is:

<Link to={{ pathname: '/category/[slug]', query: { type: 'category' } }} activeClassName="active">Some Link</Link>

Then access the queries in your Archives view via:

this.props.location.query // you could set up some conditional logic based on type

UPDATE: Without changing the url scheme

...

<Route path="/category/:slug" component={Archives} />
<Route path="/tag/:slug" component={Archives} />

// Then in Archives component you could do

class Archive extends React.Component {
   ...
   render() {
      const path = this.props.location.pathname;
      const category = path.indexOf('/category/') !== -1;
      const tag = path.indexOf('/tag/') !== -1;
      ... // some logic based on tag and category
      return {
         ...
      }    
   }
}  

Upvotes: 1

Related Questions