Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass object through Link in react router

Is it possible to pass an object via Link component in react-router?

Something like:
<Link to='home' params={{myObj: obj}}> Click </Link>

In the same way as I would pass props from the Parent to Child component.

If it's not possible what is the best way of achieving this:
I have a React + Flux app, and I render the table with some data. What I am trying to do is when I click on one of the rows it would take me to some details component for this row. The row has all of the data I need so I thought it would be great if I could just pass it through Link.

The other option would be to pass the id of the row in the url, read it in the details component and request the data from the store for by ID.

Not sure what is the best way of achieving the above...

like image 417
knowbody Avatar asked Jul 01 '15 17:07

knowbody


People also ask

How pass data with router in React?

To pass data when navigating programmatically with React Router, we can call navigate with an object. Then we can use the useLocation hook to return the object's data. const navigate = useNavigate(); navigate('/other-page', { state: { id: 7, color: 'green' } });

How do you pass props in React router?

If you are using react-router v4, you can pass it using the render prop. Sometimes you need to render whether the path matches the location or not. In these cases, you can use the function children prop. It works exactly like render except that it gets called whether there is a match or not.

How do I pass data from one page to another in React router?

You can use the Link component from react-router and specify to={} as an object where you specify pathname as the route to go to. Then add a variable e.g. data to hold the value you want to pass on.

How do I pass props from one page to another in React?

There is no way in React to set props (even though it was possible in the past). After all, props are only used to pass data from one component to another component React, but only from parent to child components down the component tree.


1 Answers

So my final conclusion on this question is that I didn't think it through properly. It seemed natural just to pass my data through the Link so I can access them in my Child component. As Colin Ramsay mentioned there is something called state in the Link but that's not the way to do it. It would work fine when the data is passed through Link only if the user clicks on something and is taken to the Child component.

The problem comes when the user accesses the url which is used in Link then there is no way to get the data.

So the solution in my case was to pass the ID in Link params and then check if my Store has the data (user accesses it via Link) and then getting this data from the Store.

Or if the data is not in the Store call the action to fetch the data from the API.

like image 176
knowbody Avatar answered Sep 23 '22 12:09

knowbody