12

I am using react-router in a SPA. In my case, the browser history is /home => /somepage1 => /another => /changepassword

when I do some thing in the route /changepassword, I wanna go to the /login route, and clear all the previous browser history and make this route /login the 1st in the history.

How can I achieve this?

Liuuil
  • 1,441
  • 3
  • 16
  • 22

3 Answers3

11

TLDR… it can be done in some conditions.

A Solution when creating browser history

My App is loaded in a new browser window, thus I'm certain the app will have a clean browser history, so I can use this to get back to the first page in the browser history:

props.history.go(-(props.history.length - 1))

If page you want to return to in the browser history was not at position 1, you can record the value of history.length at this Start page and then pass that number into this function when you're ready to go back to the Start page.

// loading start page…
const startPageIndex = props.history.length - 1

// later when ready to go back to start page…
props.history.go(-startPageIndex)

Note: When going back by using either of the above solutions, the "forward" history will still exist until the user navigates forward to create new history.

MemoryRouter - doesn’t store browser history

Use the <Memory Router> which "keeps the history of your “URL” in memory (does not read or write to the address bar)" for the flow of pages where you wish to replace the history… because it will not create a browser history.


Further Reading

Michael Jackson, the author of react-router, posted this answer regarding Reset/clear history:

There's no way for us to programmatically reset the history stack (at least in a browser, in memory history this would be trivial). If you need to clear the history stack for some reason, I'd suggest you use window.location.reload().

Further from MDN:

There is no way to clear the session history or to disable the back/forward navigation from unprivileged code. The closest available solution is the location.replace() method, which replaces the current item of the session history with the provided URL.

Beau Smith
  • 33,433
  • 13
  • 94
  • 101
1

remove all history entry

this.props.history.index=0

use in componentWillMount function where you want this will be First entry

Man
  • 742
  • 1
  • 6
  • 23
  • Welcome to StackOverflow. Answers with only code in them tend to get flagged for deletion as they are "low quality". Please read the help section on answering questions then consider adding some commentary to your Answer. – Graham Mar 08 '18 at 06:51
0

I don't believe there is elegant support for this. History is mutable however, so you can always edit history manually. Here's an example of how you might do that:

const history = this.props.history.entries

// set first entry in history to mirror the last entry
history[0] = history[history.length - 1]

// remove all but first history entry
history.length = 1
JustinTRoss
  • 677
  • 7
  • 12