Problem in redirecting programmatically to a route in react router v6

Issue

TypeError: Cannot read properties of undefined (reading 'push')

This is cause by you attempting to navigate from a navigate prop that doesn’t exist, it’s undefined.

this.props.navigate.push("/");

The useNavigate hook is only compatible with function components, so of you want/need to use navigate with a class component you must either convert AddContacts to a function component, or roll your own custom withRouter Higher Order Component to inject the “route props” like the withRouter HOC from react-router-dom v5.x did.

Solution

I won’t cover converting a class component to function component. Here’s an example custom withRouter HOC:

const withRouter = WrappedComponent => props => {
  const navigate = useNavigate();
  // etc... other react-router-dom v6 hooks

  return (
    <WrappedComponent
      {...props}
      navigate={navigate}
      // etc...
    />
  );
};

And decorate the AddContacts component with the new HOC.

export default withRouter(AddContacts);

This will now pass a navigate prop (and any others you set up) to the decorated components and this.navigate will now be defined.

Additionally, the navigation API changed from v5 to v6, it’s no longer the direct history object being used. navigate is a function instead of an object. To use you invoke the function and pass 1 or 2 arguments, the first is the target path, the second is an optional “options” object with replace and/or state key/values.

interface NavigateFunction {
  (
    to: To,
    options?: { replace?: boolean; state?: State }
  ): void;
  (delta: number): void;
}

To navigate now as follows:

this.props.navigate("/");

Leave a Comment