Search code examples
reactjsreact-routerreact-router-domreact-router-v4

Access props when using the Link element and the useLocation hook from react router


I'm trying to send props to a child component rendered with the <Link> tag from react router. I'm doing like this:

  • This is how I use the Link element in the parent component (wrapped with the useRouter hook, though no idea if I have to):
[...]
<Link
  to={{
    pathname: `/Element/${id}`,
    state: {
      info: "foo",
    },
  }}
>
  {title}
</Link>;
[...]
  • This is the component receiving that information :
import { useLocation } from "react-router-dom";

const Element = () => {
  const data = useLocation();
  console.log(data)

  return (...);
};

This is returning an object with the key state: undefined

What am I missing here? Thanks in advance


Solution

  • I finally found it, I needed to wrap both components with the withRouter hook