Home > Article > Web Front-end > How to Handle Programmatic Redirection in React Router v6 Class Components?
Programmatic navigation in React Router v6 presents a unique challenge compared to earlier versions. Class components, which were prevalent in previous iterations, encounter an undefined navigation prop, resulting in a TypeError.
React Router v6 introduced a shift in navigation strategy, moving away from the direct use of the history object. Instead, it employs navigate, a functional API that accepts a target path and optional options. This change has impacted class components, where the navigation prop is no longer automatically accessible.
To resolve this issue, there are two primary approaches:
Creating a Custom withRouter Higher-Order Component:
If converting to a function component is not feasible, you can create a custom Higher-Order Component (HOC) that essentially injects the navigation prop into the target component. Here's an example of such a HOC named withRouter:
<code class="js">const withRouter = WrappedComponent => props => { const navigate = useNavigate(); return ( <WrappedComponent {...props} navigate={navigate} /> ); };</code>
Once you have created the withRouter HOC, apply it to the target class component, AddContacts, as follows:
<code class="js">export default withRouter(AddContacts);</code>
This will expose the navigate prop to the wrapped component, allowing you to perform programmatic navigation.
In addition to the switch from class components, React Router v6 also introduced changes to the navigation API. Instead of the previously used history object, you must now invoke the navigate function, passing the target path and any optional state or replace flags.
<code class="js">this.props.navigate("/");</code>
By implementing either of the aforementioned solutions and understanding the updated navigation API, you can successfully perform programmatic redirects from class components in React Router v6.
The above is the detailed content of How to Handle Programmatic Redirection in React Router v6 Class Components?. For more information, please follow other related articles on the PHP Chinese website!