Attempting to access link to state within another component results in a typerror where state in undefined

I am attempting to pass down state via the <Link> component as such to my NextPage component:

<Link to={{pathname: `/job-run-id/${item.job_run_id}`, state: { prevPath: location.pathname }}}
>
{item.job_run_id}
</Link>

The NextPage component is being rendered via the following route:

<Route exact path="/job-run-id/:jobID">
   <NextPage />
</Route>

The NextPage component is setup as follows and just receives the props:

const NextPage = (props) => (
  <div>
    <p>previous path is: {props.location.state.prevPath}</p>
  </div>
);

Attempting to run the above code results in the following error:

TypeError: Cannot read property 'state' of undefined

Unfortunately I can’t see what I am doing wrong.

Answer

In order for the NextPage component to receive the route props (history, location, and match) it needs to be rendered by one of render, component, or children function props.

Route render methods

component

<Route
  exact
  path="/job-run-id/:jobID"
  component={NextPage}
/>

render

<Route
  exact
  path="/job-run-id/:jobID"
  render={routeProps => <NextPage {...routeProps} />}
/>

children function

<Route
  exact
  path="/job-run-id/:jobID"
  children={routeProps => (
    <NextPage {...routeProps} />
  )}
/>

For your use case, and since you aren’t passing additional props to NextPage, I suggest using the component method to render your component on the route.

An alternative if you don’t want to change how NextPage is rendered is you decorate it with the withRouter Higher Order Component to have the route props injected into it. Export the decorated NextPage component.

default export withRouter(NextPage);

Or since NextPage is a function component, use the useLocation React hook to get to the route state.

import { useLocation } from 'react-router-dom';

const NextPage = () => {
  const { state } = useLocation();
  return (
    <div>
      <p>previous path is: {state.prevPath}</p>
    </div>
  )
};