Nick
Nick

Reputation: 1541

React Router Go to Previous Page

I am trying to implement a 'go back' a step button but for whatever reason it keeps returning a 404 page not found error when doing so. It appears to only work when going to step 2 and going back to the first step (or default route)..

Route Setup:

<Router>
    <Route exact path='/onboard/' component={Main} />
    <Route path='/onboard/step2' component={Step2} />
    <Route path='/onboard/step3' component={Step3} />
    <Route path='/onboard/summary' component={Summary} />
</Router>

Go Back Function:

const handleBack = () => {
    props.history.go(-1);
};

Also, being that it's a "nested url" (so to speak), is it necessary to add the following to my onSubmit for Step2 or is there an alternative way of doing so?

const onSubmit = (data) => {
    action(data);
    props.history.push('./onboard/step2');
};

Everything following the second step seems to work with:

const onSubmit = (data) => {
    action(data);
    props.history.push('./summary');
};

Upvotes: 0

Views: 553

Answers (1)

Cyrus Zei
Cyrus Zei

Reputation: 2660

if you console.log('history', history) you should see an goBack() method that you can call

EDIT: this is how you use it props.history.goBack() add that to a button <button onClick={()=> props.history.goBack()}>go back</button>

sandbox

Upvotes: 1

Related Questions