Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-router: Passing data through routes

I'm trying to figure out the best way to pass data through my routes. I know I can use params but there are certain types of data that don't belong in params.

For example: I have an index page that displays a list of applications. Each application has a button next to it which will route you to the view for that application.

I want to pass the application itself to the Application handler. However, it doesn't make sense to pass the entire application through params. Though it does make sense to pass the application identifier to params (i.e. :id or :name)

So the way I think I should be doing this is pass the application identifier to params, then in the Application component search my ApplicationStore for the appropriate application given the identifier.

Though, wouldn't it be easier and faster to pass the application itself? Is there a way to do this. Is there a reason not to do this?

Here is some code:

<Link to="showApplication" params={{name: application.name}}>View</Link>

or

<Link to="showApplication" params={{application: application}}>View</Link>

Thanks in advance!

like image 260
BezR Avatar asked Jan 22 '15 01:01

BezR


People also ask

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

We can pass data between pages in ReactJS in both class as well as functional components using Links v5 react-route and useNavigate, useLocation (hooks) v6 of react-router.


1 Answers

The problem is that when the person refreshes, or in some other way directly loads the url, it needs to show the correct view. Because URLs are just strings, you need to represent the route as a string. You can't (easily) shove an actual application into the url.

The job of a router is to take that string (the URL) and map it to the actual code (the handler), and provide any extra data (the params, query, and/or hash).

Your job as a router user is to ensure there's enough information in the URL for the router to pick the right handler, and for the handler to have enough information to do its job (e.g. which application to show).

If the url is something like mysite.com/showApplication, there's clearly not enough information.

If it's something like:

mysite.com/showApplication/React.createClass(%7Brender%3A%20function()%7Breturn%20React.createElement('div'%2C%20null%2C%20%22I'm%20an%20application!%22%7D%7D)%3B

i.e. putting an application in the url, that's too much information, and generally a very bad idea.

But mysite.com/showApplication/applicationName is just right :-)

like image 174
Brigand Avatar answered Oct 24 '22 01:10

Brigand