How to use react-router-dom v6 navigate in class component

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 named as withRouter.js, and paste the code given below in this file:

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 help, 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);

Above Code works Perfect. And this is just a small extension.
If you want onclick function here is the code:

<div className = "row">
    <button className= "btn btn-primary" 
            onClick={this.yourFunctionHere}>RedirectTo</button>
</div>

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)