Anon
Anon

Reputation: 5

Undefined value from Link input state

I am currently trying to pass some information through React-Router-DOM's Link component to another one of my components in which I tried this:

export default function Test() {

      return(
          <div>
             <Link to={{ pathname: './NewPage', state: { testValue: true }}}>New Page</Link>
          </div>
      )
}
export default function NewPage(props) {

     console.log(props.location.state)

     return(
       <div>
         {props.location.state}
       </div>
      )

}

The error says: Cannot read property 'state' of undefined at the console.log(props.location.state) line

Note: I am using React Hooks not class

Upvotes: 0

Views: 409

Answers (2)

Brian Thompson
Brian Thompson

Reputation: 14365

The route props that react-router allows you to use must be passed into your component somehow. There are several patterns for accomplishing this, a HOC (withRouter), a hook, or by having Route pass them in directly by passing it a component prop.

Notice how you instantiate the NextPage component

<Route exact path='/NewPage' component={() => <NewPage />}/>

It is given no props.

The component prop is intended to be passed a reference to a component. You have provided an anonymous function in order to satisfy this requirement, but you lose the react-router props because of it. In order to get them you would need to pass them along (props) => <NewPage {...props}/> (But please don't do that, use render if you really want to use a function).

Simply cut out the arrow function and give the component prop the component reference, and it will get the rout props it needs:

<Route exact path='/NewPage' component={NewPage}/>

Since you're using functional components, I would recommend rendering your components as Route children, and using the hooks to access the react-router values.

<Route exact path='/NewPage'>
  <NewPage />
</Route>

....

export default function NewPage(props) {
  let location = useLocation();

  return (
    <div>
      {location.state}
    </div>
  )
}

This syntax allows you to easily add other props that you may need to NewPage, while still being able to use the route props through hooks.

Upvotes: 0

Rogelio
Rogelio

Reputation: 1094

I'd suggest using search or hash rather than state as i'm guessing you want your data to persist; https://reactrouter.com/web/api/Link

<Link
  to={{
  pathname: "/courses",
  search: "?sort=name",
  hash: "#the-hash",
 }}
/>

and then you can access it just the way you did in using props.location.search or props.location.hash you can refer to the docs to confirm the properties https://reactrouter.com/web/api/location

Upvotes: 0

Related Questions