Search code examples
javascriptreactjsreact-routerreact-router-dombrowser-history

Delete a particular entry from history in 'react-router-dom


consider this scenario. The user moves from Page1(/page1) to Page2(/page2) to page3(/page3) . now if he press the back button obviously he will go to Page2(/page2).

But here how can I delete the Page2(/page2) entry from history so that he will be taken to the Page1(/page1) on back button click from Page3(/page3)


Solution

  • If you know that you don't want to go back to page 2, you can replace page 2 in history when you leave for page 3. You can do this using <Link to={url} replace /> if there is a link, or you can use history.replace(url). (You can import history from 'history', it is a subdependency of 'react-router-dom'.)

    If you only know that you don't want to go back once you reach page 3, I don't know of any clean way to remove a previous entry in history.