0

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>
Gautam Kothari
  • 301
  • 2
  • 8
  • this post may help you: https://stackoverflow.com/questions/58548767/react-router-dom-useparams-inside-class-component – nima Oct 23 '21 at 14:42
  • You can use `this.props.history.push("/login");`[https://stackoverflow.com/questions/59402649/how-can-i-use-history-pushpath-in-react-router-5-1-2-in-stateful-component] – ABDULLOKH MUKHAMMADJONOV Oct 23 '21 at 14:52
  • Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'push') Got this error when used this.props.history.push("/login"); – Gautam Kothari Oct 23 '21 at 14:58

1 Answers1

1

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)

  • Thanks @cedavitkovac for your answer . This worked for me but I am using connect()(LoginComponent) method . Can I use withRouter and connect both while exporting component – Gautam Kothari Oct 23 '21 at 15:22
  • I am not sure what exactly do you mean. Can you show that part of code? If you are thinking of child component of the component that is wrapped inside withRouter I guess you can pass the retrieved history object to it simply through props from the parent. – cedavitkovac Oct 23 '21 at 16:00