DEV Community

Discussion on: Need Custom Back-Button in ReactJS

Collapse
 
darksmile92 profile image
Robin Kretzschmar

You can use the React Training documentation as a good starting point.

Normally you would to something like this to navigate via anchors:

import { Link } from "react-router-dom";
<Link to="/">Home</Link>

But as you want to route via code, you would want to do something like this:

import { withRouter } from "react-router"

const BackButton = ({history, location}) => (<Button className="backbutton" onClick={() => history.push('/home')}>GoBack!</Button>);

export default withRouter(BackButton);

First, use the HOC withRouter to be able to get the history object in via the properties (destructuring history and location in this example).
Then call .push() with the path you want to navigate to as parameter.

I don't recommend the second way, but here is another one:
history.goBack().