DEV Community

Discussion on: Need Custom Back-Button in ReactJS

Collapse
 
darksmile92 profile image
Robin Kretzschmar

Could you please be more specific?
To help you, the following information would be necessarry:

  • How do you route? (React-Router, NextJS router, ...)
  • Do you want to go back via history or push the URL to the history? (adds a new entry to the browsing history)

What do you expect from a "generic custom" back button?
Most of the time it is sufficient to route back (depending on answers to the questions above) in the onClick event.

Collapse
 
amarj3142 profile image
amarj3142

thanks Robin for instant reply,
i am using React-Router.
and want to go back via history.

have to place one custom button in header component and whenever i will go on some page have to come back on render page. just like any browser back arrow works.

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().