javascript - how to get the previous route the user came from in react - Stack Overflow

I am trying to get the url of the previous page I came from in react.So if I came from xxxregister, a

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?

Share Improve this question asked Apr 23, 2021 at 19:24 GianlucaGianluca 9901 gold badge16 silver badges41 bronze badges 4
  • 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 out react-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
Add a ment  | 

2 Answers 2

Reset to default 2

We 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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744380934a4571425.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信