misakimichy
misakimichy

Reputation: 163

React Router: How to render different components with the same route conditionally

How can I render different components with the same route path with React router but the slug input types are different(int vs string)?

<Switch>
    <Route exact path={['/music/:category', '/products/:category']} component={List} />
    <Route exact path="/products/:productId" component={Details} />
</Switch

I want to render List component when the path is /products/:category when the slug is a string. I also want to use the same path to render the Details component when its slug, :productId, is an integer.

I was thinking this might work, but it doesn't. This renders Details component whether or not the condition.

{pathname.includes('/products') && typeof parseInt(pathname.split('/products/')[1]) === 'number'
  ? (
    <Route exact path="/products/:id" component={Details} />
  ) : (
    <Route exact path={['/music/:slug', '/products/:slug']} component={List} />
)}

Thank you!

Upvotes: 1

Views: 1552

Answers (1)

Yadab
Yadab

Reputation: 1883

You can make use of render props of Route to validate the params.

<Route
    path="/products/:id"
    render={({ match: { params: { id } } }) => {
      if(isNaN(id) {
        <Route exact path={['/music/:slug', '/products/:slug']} component={List} />
      } else {
        <Route exact path="/products/:id" component={Details} />
      }
    }}
/>

Upvotes: 2

Related Questions