Home > Article > Web Front-end > How to Programmatically Redirect in React Router v6 from a Class Component?
Problem:
When attempting to programmatically redirect to a different route from a class component in React Router v6, you may encounter the following error:
TypeError: Cannot read properties of undefined (reading 'push')
This error occurs because the navigate prop is not available on class components in v6. Instead, it is only accessible to function components.
Solution:
There are two ways to resolve this issue:
Convert the class component to a function component:
Create a custom withRouter HOC:
import withRouter from './withRouter'; // Change this to the path of your custom HOC file export default withRouter(AddContacts);
This will provide the navigate prop to the AddContacts component.
Additional Note:
In React Router v6, the navigation function is no longer an object but a function that takes in the target path as the first argument and an optional options object as the second argument.
interface NavigateFunction { ( to: To, options?: { replace?: boolean; state?: State } ): void; (delta: number): void; }
This means that the syntax for navigation has also changed. To navigate to a route using navigate, invoke the function as follows:
// Example usage this.props.navigate("/");
By following either of the above solutions, you should be able to programmatically redirect to different routes in React Router v6.
The above is the detailed content of How to Programmatically Redirect in React Router v6 from a Class Component?. For more information, please follow other related articles on the PHP Chinese website!