Multiple params with React Router

ReactjsReact Router

Reactjs Problem Overview


I use React 15.0.2 and React Router 2.4.0. I want to pass multiple params to my route and I'm not sure how to do it in the best way:

<Route name="User" path="/user" component={UserPage}>	
	<Route name="addTaskModal" path="/user/manage:id" component={ManageTaskPage} />
</Route>

And what is want is something like:

 <Route name="User" path="/user" component={UserPage}>	
	<Route name="addTaskModal" path="/user/manage:id:type" component={ManageTaskPage} />
</Route>

Reactjs Solutions


Solution 1 - Reactjs

As @alexander-t mentioned:

path="/user/manage/:id/:type"

If you want to keep them optional:

path="/user/manage(/:id)(/:type)"


React Router v4

React Router v4 is different than v1-v3, and optional path parameters aren't explicitly defined in the documentation.

Instead, you are instructed to define a path parameter that path-to-regexp understands. This allows for much greater flexibility in defining your paths, such as repeating patterns, wildcards, etc. So to define a parameter as optional you add a trailing question-mark (?).

So, to define optional parameters, you can do:

path="/user/manage/:pathParam1?/:pathParam2?"

i.e.

<Route path="/user/manage/:pathParam1?/:pathParam2?" component={MyPage} />

Whereas, The mandatory Parameters are still same in V4:

path="/user/manage/:id/:type"

To access PathParam's value, you can do :

this.props.match.params.pathParam1

Solution 2 - Reactjs

<Route path="/:category/:id" exact component={ItemDetails} />

In the component, using useParams from react-router-dom,

import { useParams } from 'react-router-dom'
export default function ItemDetails(props) {

const {id, category} = useParams();
return (
    <div className="">
        {id}
        {category}
    </div>
)

Here is the solution, without props and using routing library.

Solution 3 - Reactjs

Try this

<Route name="User" path="/user" component={UserPage}>  
  <Route name="addTaskModal" path="/user/manage/:id/:type" component={ManageTaskPage} />
</Route>

Solution 4 - Reactjs

For the optional param fields, for some reason it works fine without the slash before the colon inside the braces (). React-router 2.6x

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFrix GView Question on Stackoverflow
Solution 1 - ReactjsTomas RandusView Answer on Stackoverflow
Solution 2 - ReactjsBikram NathView Answer on Stackoverflow
Solution 3 - ReactjsSultan AslamView Answer on Stackoverflow
Solution 4 - ReactjsHarView Answer on Stackoverflow