Home > Back-end >  How to redirect to a class component from another class component in reactjs
How to redirect to a class component from another class component in reactjs

Time:10-24

I know we use history.push() in functional component and react routing for redirection. But in class component how can we redirect on a button click

function onSubmit(){
console.log("Cannot use usehistory in this function as this is a class component")
}

//Link is not working in below code

<Link to ="/login">
<Button onClick={this.onSubmit}>Submit</Button>
</Link>

CodePudding user response:

If you want to do it with history you can use withRouter higher order component provided by 'react-router'. You just need to import {withRouter}

import {withRouter} from 'react-router';

and export your Component where the button is as :

export default withRouter(Component);

Now you can access hitory object via props. (this.props.history)

  • Related