Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the previous route the user came from in react

I am trying to get the url of the previous page I came from in react.

So if I came from xxx.com/register, and am now on ...com/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?

like image 351
Gianluca Avatar asked Sep 07 '25 01:09

Gianluca


1 Answers

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 )
like image 101
GMKHussain Avatar answered Sep 08 '25 23:09

GMKHussain