Abhijeet Srivastava
Abhijeet Srivastava

Reputation: 341

How to go back to previous page using back button/Link click using react-router-dom

I am using React 15.6 and react-router 4

I have 5 pages in app A, B, form1, form2, C. form1 and form2 has BACK and NEXT button. Here is the navigation flow -

(A/B) --> form1 --> form2 --> C.

User can come to form1 from either A or B.

My question is - If user is coming from A to form1 and then to form2 then while going back to previous pages how can user go to A again on clicking BACK button on form1.

If there is only A then we could do it using

<Link to="path/to/A"/>

on form1 BACK button click.

But if we have both A and B as possible path then we can not decide whether user came to form1 from A or B.

Can some help how we can manage the previous path state in this scenario.

Upvotes: 4

Views: 6898

Answers (1)

Kenneth Truong
Kenneth Truong

Reputation: 4176

I believe your case is very similar to the auth example where you have to remember the page where the user came from https://reacttraining.com/react-router/web/example/auth-workflow

In your page A and page B you can add a link where

<Link 
  to={{ 
    pathname: '/form1',
    state: { from: props.location } // or '/A' or '/B'
  }}
/>

In Form1 you need to have access to location so you might need to use withRouter

<Link to={props.location.state.from}>
  Back
</Link>

If you need to go to Form2 and still remember this path then you probably should just keep passing the state along

Upvotes: 6

Related Questions