Home > Article > Web Front-end > How to Programmatically Redirect in React Router v6 with Class Components?
Facing a TypeError: Cannot read properties of undefined (reading 'push') while attempting to navigate using the useNavigate hook in a class component.
In React Router v6, useNavigate is only compatible with function components. When trying to use it in a class component (AddContacts), it remains undefined, resulting in the error.
To resolve this issue, there are two options:
Refactor the AddContacts class component to a function component. This will allow you to use the useNavigate hook directly within the function.
Create a custom withRouter HOC to inject the route props, including useNavigate, into the AddContacts component.
Here's an example custom withRouter HOC:
const withRouter = (WrappedComponent) => (props) => { const navigate = useNavigate(); return ( <WrappedComponent {...props} navigate={navigate} /> ); };
Then, decorate the AddContacts component with the HOC:
export default withRouter(AddContacts);
This will pass the navigate prop to the AddContacts component and allow you to use it as expected.
In React Router v6, the navigation API has changed. The history object is no longer directly used. Instead, there's a navigate function that takes one or two arguments: a target path and an optional "options" object for replace or state.
To navigate programmatically, use the following syntax:
this.props.navigate('/');
The above is the detailed content of How to Programmatically Redirect in React Router v6 with Class Components?. For more information, please follow other related articles on the PHP Chinese website!