0

With React Router v5.1's additions of useParams, useHistory, and useLocation, along with changing coding conventions brought with react-hooks and functional components, it's gotten confusing trying to figure out the intended way to use a contemporary version of react-router.

When programming navigation with react router, how does one properly pass parameters between different urls?

For example, say I have a component, called component_a, that calls the following when clicked:

history.push("/home"); //history is defined as the return value of useHistory() from react-router-dom

What is the proper way for me to pass some of component_a's properties to another component called component_b? Component_b is rendered like so:

<Route path="/home" component={component_b}/>


I'm aware that history.push() takes a second parameter [state]. However I didn't see any examples of it in the docs. I also couldn't find a description of it.

I'm also aware of useParams(), however what if there are too many variables to pass through the url itself?

Parm
  • 538
  • 1
  • 7
  • 19
  • Does this answer your question? [How to pass params with history.push/Link/Redirect in react-router v4?](https://stackoverflow.com/questions/44121069/how-to-pass-params-with-history-push-link-redirect-in-react-router-v4) – Gonzalo.- Apr 22 '20 at 21:29
  • It does, however I'm not sure if that answer is still valid for v5.1. It definitely seems out of context because it makes no mention of useParams, useHistory, useLocation, and more that were added with react router 5.1 – Parm Apr 22 '20 at 21:44
  • it does. The hooks are just ways to access the same objects as before. – Gonzalo.- Apr 22 '20 at 22:11

1 Answers1

0

hooks are there so you don't have to use HOC withRouter anymore to get what you need from router.

trough URL you should only pass data that natively belongs to URL (eg. route name, ID, search params, etc)

with state you can pass whatever you want in theory but in practice you'll probably pass some smaller chunks of data (eg. flags, ID)

with router v5 there's also a new way of constructing the Route

<Route path="/home">
  <YourComponent prop1 prop2 />
</Route>

and there you define all of your component props

for everything else you should use app store like Redux, MobX or Context that you'll update before your history.push("/home"); and access it once you're in <YourComponent />

fila90
  • 1,439
  • 11
  • 11