0

I am working on a react web app and i am using react router. I want to pass data from the NavLink to my Movies component. The NavLink is shown below.


<ul>
   <li id="movies">
       <NavLink exact to = {{pathname: "/", state:{page: 1}}}  > Movies </NavLink>
   </li>
</ul>

In my router, i want to redirect to movies/all/1 from the landing page. My routes are:


 <Route exact path="/" render={() => <Redirect to="/movies/all/1" />} />
 <Route exact path = "/movies/:genre/:genrePage" component = {Movies} />

In the Movies component, i can access the route parameters but i am failing to access the data, {page: 1}, passed from NavLink via location props. I keep getting undefinedas the value of props.location.state. How do i go about this? I don't want the data i am passing to be in the url.

EDIT

Perhaps to clarify. The question below partly answers my question.

However i am still failing to access the data passed from Link when the page is first loaded and then redirected from root path / to /movies/all/1. It is only accessible after Link has been clicked.

nibble
  • 314
  • 2
  • 10
  • Does this answer your question? [ReactJS - Pass props with Redirect component](https://stackoverflow.com/questions/52064303/reactjs-pass-props-with-redirect-component) – Mateen Jul 21 '20 at 19:23
  • A possible duplicate: https://stackoverflow.com/questions/52064303/reactjs-pass-props-with-redirect-component – Mateen Jul 21 '20 at 19:24
  • Check the edit i have made above – nibble Jul 22 '20 at 14:18

1 Answers1

1

Redirect component doesn't pass location.state to the next route (i.e /movies/all/1).

If you want to do that, you need to get location.state from your Route / and pass it down to Redirect.

It would look something like that:

<Route exact path="/" render={({ location }) => <Redirect to={{ pathname: "/movies/all/1", state: location.state }} />} />
boertel
  • 544
  • 2
  • 6
  • It works but only after the link has been clicked. I want the data to be passed immediately on page load. If a visitor reaches the site, he/she is redirected from `/` page to `movies/all/1`. That is when the value of `state` is `undefined`. If you click `NavLink` first, the data is passed fine. – nibble Jul 22 '20 at 07:54
  • I don't think you can define the history state on page load. The way you could do that is inside your `Movies` component, wherever you access `page` value, you need to do something like `const page = location.state?.page || 1;` so it would default to `1` when `undefined` – boertel Jul 23 '20 at 00:57
  • That is the solution i have settled for. Thanks a bunch. – nibble Jul 23 '20 at 06:24