Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple params with React Router

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> 
like image 430
Frix G Avatar asked Jun 08 '16 07:06

Frix G


People also ask

How do I get params in react router Dom?

To get path params in React Router, we can use the useParams hook. We create the Child component that calls the useParams hook to return an object with the route params in the URL. And we render the value of the id param on the page. In App , we have 2 links that goes to routes with different id param values.

How do you pass additional data while redirecting to a route in react?

Using Link So when we click on the Register link, it will redirect to the /register route. But Link also allows us to pass additional data while redirecting. Here, at the place of data_you_need_to_pass , we can pass a string or object , array and so on and in the /register route we will get that data in props.

How do you pass query parameters in react?

To pass in query parameters, we just add them to the Link s to props as usual. For example, we can write the following: We first defined the useQuery Hook to get the query parameters of the URL via the URLSearchParams constructor. We get the useLocation() s search property.


1 Answers

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 
like image 110
Tomas Randus Avatar answered Oct 24 '22 17:10

Tomas Randus