Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-router: Change URL and clear history

I have the following scenario:

A user opens an activation link; after the user has completed the activation process, the system will move them to another page.
I don't want to keep the activation link in the browser's history because when the the user goes back they will get to the activation step again.

How do I replace the history of a browser to remove certain requests from my application?

like image 841
Thu Quoc Nguyen Avatar asked Sep 27 '16 02:09

Thu Quoc Nguyen


People also ask

How do you clear history on react router?

push(`/route`); This will clear the history and change for a new one.

Does react router change URL?

Using react-router-dom to Change URL Path and Render Components. The react-router-dom package is great for rendering different React components based on the url path. Therefore, React components can lead to others by changing the url path.

How do I change the default URL in react?

Use the Navigate element to set a default route with redirect in React Router, e.g. <Route path="/" element={<Navigate to="/dashboard" />} /> . The Navigate element changes the current location when it is rendered. Copied!

Is history mutable in react router?

history is mutable The history object is mutable. Therefore it is recommended to access the location from the render props of <Route> , not from history.


1 Answers

In ReactJs you should use browserHistory for this purpose. This takes care of your histories and you don't need to implement those functions on your own.

browserHistory has 2 methods push() and replace() which do the same functions as @fazal mentioned in his answer but in a better way.

So if you want to avoid user going back to previous state you would need to use browserHistory().replace

Start with importing it into your code:

import {browserHistory} from 'react-router' 

After user has activated you do following:-

browserHistory.replace(//your new link) 
like image 57
Harkirat Saluja Avatar answered Oct 03 '22 21:10

Harkirat Saluja