1

Below is my index.js file,it contains the routing path to all the components.When I navigated to one component from another how can I retrieve the previous and current paths ?

import React from 'react';
import ReactDom from 'react-dom';
import Login from './testApp/login.js';
import Register from './testApp/register.js';
import { BrowserRouter as Router, Route} from "react-router-dom";
import fetch from 'isomorphic-fetch';
class App extends React.Component {
    "eqeqeq":false;
    constructor(props) {
        super(props);
        this.handleSubmit=this.handleSubmit.bind(this);
        this.handleTest=this.handleTest.bind(this);
        this.state={name:{}};
    }
    Greeting() {
        return <h1>ffgdf</h1>
    }
    httpCalling(data) {
       fetch('http://localhost:8080/testingonly', {
        method:'POST',
        mode:'CORS',
        body:JSON.stringify(data),
        headers:{
            'Content-Type':'application/json',
             'Accept': 'application/json'
        }
        }).then(res => res.json()).then(result => {
            localStorage.setItem('myData',JSON.stringify(result));
        });
        const item=localStorage.getItem('myData');
        console.log(JSON.parse(item));
    }
    handleSubmit(data) {
        console.log("++++data++++++++");
        console.log(data);
        console.log("++++data++++++++");
        this.httpCalling(data);
    }


    render() {
        return (

           <Router>
               <div>
                <Route exact path="/" render={(props) => <Login  onSubmit={this.handleSubmit} {...props} />}/>
                {/* add the routes here */}
                <Route path="/test" component={this.Greeting}/>
                <Route path="/register" render={(props) => <Register  />} />
                </div>
          </Router> 
        ) 

    }
}
ReactDom.render(<App />,document.getElementById('root'));

In the above example you can see that all components are defined in the render function of App component.So when I navigated from one component to another how can I detect the previos and current routes ?

Pranab V V
  • 1,386
  • 5
  • 27
  • 53

1 Answers1

-4

In your case, basically the routes are getting changed. So you could use the browser window methods to get the current previous routes.

To get the previous route:

window.document.referrer

To get the current route:

window.location.href

You then can use any string methods to extract what you need.

Joby Joseph
  • 2,177
  • 3
  • 15
  • 19
  • thank you.Is the following solution [https://stackoverflow.com/questions/36654475/react-router-how-to-get-the-previous-route-in-onenter-handler] is correct ?It doesn't worked for me – Pranab V V Mar 12 '18 at 11:58
  • `window.document.referrer` isn't updated each time you navigate to a new route. See here for a real solution using [React Router](https://stackoverflow.com/questions/39288915/detect-previous-path-in-react-router). – kylebebak Apr 18 '19 at 19:04