Home > Net >  Is it possible to render different components depending on a url params value within the same url in
Is it possible to render different components depending on a url params value within the same url in

Time:09-24

So basically title is my question. Is it possible to achieve something like this with only url paramater change:

<Route path={'/users/:id'} component={()=> UsersPage}/>

<Route path={'/users/:filterOption'} component={()=> UsersList}/>

CodePudding user response:

Yes, we can do that in react-router, Just check this article, it has best example for Dynamic URL Parameters.

CodePudding user response:

Yes, absolutely you can. The Router component inclusively matches and renders routes (as opposed to the Switch component that exclusively matches them). This means the Router will render all routes and redirects that are matched by the path prop.

Given path `"/users/someValue":

<Router>
  <Route path={'/users/:id'} component={()=> UsersPage}/>
  <Route path={'/users/:filterOption'} component={()=> UsersList}/>
</Router>

Both components can be matched and rendered.

Note about Route component prop!

Route render methods

When you use component (instead of render or children) the router uses React.createElement to create a new React element from the given component. That means if you provide an inline function to the component prop, you would create a new component every render. This results in the existing component unmounting and the new component mounting instead of just updating the existing component. When using an inline function for inline rendering, use the render or the children prop.

This means you should not use the component prop if you are providing a function. Instead do one of the following

<Router>
  <Route path={'/users/:id'} component={UsersPage}/>
  <Route path={'/users/:filterOption'} component={UsersList}/>
</Router>

or

<Router>
  <Route path={'/users/:id'} render={()=> <UsersPage />}/>
  <Route path={'/users/:filterOption'} render={()=> <UsersList />}/>
</Router>

or

<Router>
  <Route path={'/users/:id'}>
    <UsersPage />
  </Route>
  <Route path={'/users/:filterOption'}>
    <UsersList />
  </Route>
</Router>
  • Related