javascriptreactjsreact-routerhistory

Is there any way to clear react history in react?


I have a Web application which is targeted for mobile users but since our client doe not want a mobile app, it is developed using React. I have implemented in-app routing using React Router. I use useHistory hook so basically use history object for navigation. I want to keep the in-app navigation and browser navigation in sync.

Now the requirement is I have a payments page. When user completes his payment procedure, user should not be able to go back to any of the pages involved in the payment process. Or simply if user hits back button, he should land up on home page. So I thought of clearing the history so that user wont be able to go back. But it seems there is no way in react to clear the history.

Please let me know if anyone knows any solutions.


Solution

  • Generally in a purchase flow you should be using redirect (history.replace) to step through the payment pages. Should the user then press the back button then they would then do a back navigation to the page they were on before they entered the "restricted navigation flow".

    Alternatively you can try using a Prompt:

    Used to prompt the user before navigating away from a page. When your application enters a state that should prevent the user from navigating away (like a form is half-filled out), render a <Prompt>.

    See the Preventing Transitions demo.

    You could use this to capture the attempt to do a back navigation within a "restricted navigation flow" and then either block navigation or imperatively redirect to a route of your choice, i.e. history.replace("/") to bounce a user to all the way back to a homepage.