I am trying to get the url of the previous page I came from in react.
So if I came from xxx/register
, and am now on ../profile
, then how do I log that in the console?
I have no clue where to start. Does anyone know how to do this? Is this possible in react
? Should I use js
instead?
I am trying to get the url of the previous page I came from in react.
So if I came from xxx./register
, and am now on .../profile
, then how do I log that in the console?
I have no clue where to start. Does anyone know how to do this? Is this possible in react
? Should I use js
instead?
-
if you are using react router then
history.goBack();
is what you are looking for. – Medi Commented Apr 23, 2021 at 19:26 - but with history.goBack(), I cannot log that, because it takes me back to that page no matter what. I pretty much just want to log it, so I can use it in an if statement after – Gianluca Commented Apr 23, 2021 at 19:28
-
If you want to see where the user came from it is stored in
document.referrer
. This is not framework-specific. If you want to keep the track of routes from within you app. Check outreact-router
. – webduvet Commented Apr 23, 2021 at 19:38 - @webduvet appreciate the answer! document.referrer works, but it isn't consistent within the app for paths. I think react-router would be better. Could you point me into the right direction for this one plz :) – Gianluca Commented Apr 23, 2021 at 19:46
2 Answers
Reset to default 2We can access the previous page using useHistory()
import { useHistory } from "react-router-dom";
//...
const history = useHistory();
//...
<div onClick={() => { history.push( 'pages/previous-page', { from: "previous-page" }) }>
Previous Page
</div>
On next page you can check by this code
console.log("Landed on this page from ", history.location.state.from )
First off, you ask in the last sentence if you should use JS instead. React is a JavaScript library, thus you are already using JS and everything that you can do in your current version of JS, you can do in React.
Next, the History ponent is what you're looking for.
Here is a very prehensive guide on history: https://reactrouter./web/api/history.
Basically, you view the history, which is an array, from inside of your ponent. You can then either pull different values from the array or even push new values into the array, such as different pages on your website.