Ivan Semochkin
Ivan Semochkin

Reputation: 8897

What is a best practice to pass props through react-router <Link />?

I use react-router4. I want to pass a several props to one of my form components to initialize state, via Link component. I found two ways to do it:
Pass it via state.

<Link to={{pathname:'/orders/', state:{prop1: 'p1', prop2: 'p2', prop3: 'p3'}}} />

And path it via query params by changing url to /orders/:prop1/:prop2/:prop3

<Link to='/orders/p1/p2/p3' />  

React full of best practice and recommendations how to use it properly. I want to know is there any recommendation how to pass props via <Link /> component.
When I should use query params and when state?

Upvotes: 2

Views: 786

Answers (1)

Zac Kwan
Zac Kwan

Reputation: 5747

It kind of depend on the type of app you are building and whether when navigating to the next component do you already have all the required props?

For example, if a app depend on a external api to fetch order detail. When on the orders page, I prefer to use a <Link to='/orders/1235' /> and fetches the order number base on the pathname received. Reason is because in the orders page, I do not have all the detail about orderId 1235 yet.

For most cases where I use pass via state are usually to toggle the UI only.

<Link to={{pathname:'/home/', state:{newUser: true} }}/>

So in my component, I have something that check if is newUser, i will display a instruction banner.

Upvotes: 2

Related Questions