react-router (v4) how to go back?
I think the issue is with binding:
constructor(props){ super(props); this.goBack = this.goBack.bind(this); // i think you are missing this}goBack(){ this.props.history.goBack();}.....<button onClick={this.goBack}>Go Back</button>
As I have assumed before you posted the code:
constructor(props) { super(props); this.handleNext = this.handleNext.bind(this); this.handleBack = this.handleBack.bind(this); // you are missing this line}
UPDATED:
Now we have hook, so we can do it easily by using useHistory
const history = useHistory()const goBack = () => { history.goBack()}return ( <button type="button" onClick={goBack}> Go back </button>);
ORIGINAL POST:
this.props.history.goBack();
This is the correct solution for react-router v4
But one thing you should keep in mind is that you need to make sure this.props.history is existed.
That means you need to call this function this.props.history.goBack();
inside the component that is wrapped by < Route/>
If you call this function in a component that deeper in the component tree, it will not work.
EDIT:
If you want to have history object in the component that is deeper in the component tree (which is not wrapped by < Route>), you can do something like this:
...import {withRouter} from 'react-router-dom';class Demo extends Component { ... // Inside this you can use this.props.history.goBack();}export default withRouter(Demo);
For use with React Router v4 and a functional component anywhere in the dom-tree.
import React from 'react';import { withRouter } from 'react-router-dom';const GoBack = ({ history }) => <img src="./images/back.png" onClick={() => history.goBack()} alt="Go back" />;export default withRouter(GoBack);