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 }}}

The NextPage component is being rendered via the following route:

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

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

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

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.


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




  render={routeProps => <NextPage {...routeProps} />}

children function

  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 (
      <p>previous path is: {state.prevPath}</p>