Dealing with [history.push] deprecation in react-router-V6
As support for history is deprecated in react-router V6, so in order to navigate user on successful completion of an event we can use navigate
In the react-router-dom v6, the support for history has been deprecated but instead of it navigate has been introduced. if you want to redirect user to a specific page on success of a specific event then follow the steps given below:
Create a file withRouter.js
import { useNavigate } from 'react-router-dom';
export const withRouter = (Component) => {
const Wrapper = (props) => {
const navigate = useNavigate();
return (
<Component
navigate={navigate}
{...props}
/>
);
};
return Wrapper;
};
Now, in whichever class based component you want to redirect the user to a specific path/component, import the above withRouter.js file there and use this.props.navigate('/your_path_here') function for the redirection.
For your reference, a sample code showing the same has been given below:
import React from 'react';
import {withRouter} from '.your_Path_To_Withrouter_Here/withRouter';
class Your_Component_Name_Here extends React.Component{
constructor(){
super()
this.yourFunctionHere=this.yourFunctionHere.bind(this);
}
yourFunctionHere()
{
this.props.navigate('/your_path_here')
}
render()
{
return(
<div>
Your Component Code Here
</div>
)
}
}
export default withRouter(Your_Component_Name_Here);
In this way we can navigate use to particular URL path on successful completion of an event.