103

I have to implement some business logic depending on browsing history.

What I want to do is something like this:

reactRouter.onUrlChange(url => {
   this.history.push(url);
});

Is there any way to receive a callback from react-router when the URL gets updated?

Shubham Khatri
  • 211,155
  • 45
  • 305
  • 318
Aris
  • 1,978
  • 5
  • 16
  • 25
  • What version of react-router are you using? That will determine the best approach. I will provide an answer once you update. That being said, the [withRouter](https://reacttraining.com/react-router/web/api/withRouter) HoC is probably your best bet for making a component location aware. It will update your component with new ({match, history, and location }) anytime a route changes. This way you don't need to manually subscribe and unsubscribe to events. Meaning it is easy to use with functional stateless components as well as class components. – Kyle Richardson Jul 29 '17 at 16:36

8 Answers8

130

You can make use of history.listen() function when trying to detect the route change. Considering you are using react-router v4, wrap your component with withRouter HOC to get access to the history prop.

history.listen() returns an unlisten function. You'd use this to unregister from listening.

You can configure your routes like

index.js

ReactDOM.render(
      <BrowserRouter>
            <AppContainer>
                   <Route exact path="/" Component={...} />
                   <Route exact path="/Home" Component={...} />
           </AppContainer>
        </BrowserRouter>,
  document.getElementById('root')
);

and then in AppContainer.js

class App extends Component {
  
  componentWillMount() {
    this.unlisten = this.props.history.listen((location, action) => {
      console.log("on route change");
    });
  }
  componentWillUnmount() {
      this.unlisten();
  }
  render() {
     return (
         <div>{this.props.children}</div>
      );
  }
}
export default withRouter(App);

From the history docs:

You can listen for changes to the current location using history.listen:

history.listen((location, action) => {
      console.log(`The current URL is ${location.pathname}${location.search}${location.hash}`)
  console.log(`The last navigation action was ${action}`)
})

The location object implements a subset of the window.location interface, including:

**location.pathname** - The path of the URL
**location.search** - The URL query string
**location.hash** - The URL hash fragment

Locations may also have the following properties:

location.state - Some extra state for this location that does not reside in the URL (supported in createBrowserHistory and createMemoryHistory)

location.key - A unique string representing this location (supported in createBrowserHistory and createMemoryHistory)

The action is one of PUSH, REPLACE, or POP depending on how the user got to the current URL.

When you are using react-router v3 you can make use of history.listen() from history package as mentioned above or you can also make use browserHistory.listen()

You can configure and use your routes like

import {browserHistory} from 'react-router';

class App extends React.Component {

    componentDidMount() {
          this.unlisten = browserHistory.listen( location =>  {
                console.log('route changes');
                
           });
      
    }
    componentWillUnmount() {
        this.unlisten();
     
    }
    render() {
        return (
               <Route path="/" onChange={yourHandler} component={AppContainer}>
                   <IndexRoute component={StaticContainer}  />
                   <Route path="/a" component={ContainerA}  />
                   <Route path="/b" component={ContainerB}  />
            </Route>
        )
    }
} 
cuniculus
  • 636
  • 8
  • 15
Shubham Khatri
  • 211,155
  • 45
  • 305
  • 318
  • 1
    he's using v3 and the second sentence of your answer says "_Considering you are using `react-router v4`_" – Kyle Richardson Jul 29 '17 at 16:50
  • 1
    @KyleRichardson I think you misunderstood me again, I certainly have to work on my english. I meant that if you are using react-router v4 and you are using history object then you need to wrap your component with `withRouter` – Shubham Khatri Jul 29 '17 at 16:51
  • @KyleRichardson I you see my complete answer, I have added ways to do it in v3 also. One more thing, the OP commented that he is using v3 today and I had answerd on the question yesterday – Shubham Khatri Jul 29 '17 at 16:52
  • 1
    @ShubhamKhatri Yes but the way your answer reads is wrong. He is not using v4... Also, why would you use `history.listen()` when using `withRouter` already updates your component with new props every time routing occurs? You could do a simple comparison of `nextProps.location.href === this.props.location.href` in `componentWillUpdate` to perform anything you need to do if it has changed. – Kyle Richardson Jul 29 '17 at 16:56
  • @KyleRichardson as I said OP mentioned that he is using v3 today and there are multiple ways to do it, 1. make use of history from withRouter 2. make use of history from history package 3. or do a props comparison. However I think do check is compentWillUpdate is not the best solution as it is fired everytime the component needs to update – Shubham Khatri Jul 29 '17 at 17:00
  • @ShubhamKhatri ok :) Sorry if I find your answer hard to follow. It looks like you're suggesting to use `withRouter` AND `history.listen()`. – Kyle Richardson Jul 29 '17 at 17:01
  • @KyleRichardson, I would say, if you are using react-router v4 , follow the first example using history object which is available as prop after you wrap your component with withRouter or use history.listen() or browserHistory.listen() in case of react-router v3 – Shubham Khatri Jul 29 '17 at 17:04
  • @ShubhamKhatri I would use `withRouter` and do props comparison instead of `history.listen()`. – Kyle Richardson Jul 29 '17 at 17:06
  • @KyleRichardson as I said there are multiple ways to do it, I prefer history.listen and it is also suggessted on the github issue https://github.com/ReactTraining/react-router/issues/3554 – Shubham Khatri Jul 29 '17 at 17:07
  • 1
    @Aris, did you get a change to try it – Shubham Khatri Aug 03 '17 at 20:09
  • I used react router v4 with React Router Config. I'm not able to use withRouter to wrap my App component. It raise this error:Uncaught Error: You should not use or withRouter() outside a . My app component render logic : return {renderRoutes(routes)}; – M.Abulsoud Jan 25 '19 at 17:49
  • @ShubhamKhatri When I change the route using `history.push`, the `listen` doesn't fire, any idea? btw when route changes via `Link`, everything works fine. – Mehdi Dehghani May 29 '19 at 05:31
  • @MehdiDehghani If could be possible that you are using custom history in Router and using push method custom history object whereas you listen to history from props. If thats not the case, could you please provide more details, possibly in a new post – Shubham Khatri May 29 '19 at 05:33
  • @ShubhamKhatri What you mean by "you are using custom history in Router"? I passed the props to the child component, then in `componentDidMount` add the listener, and `unlisten` it in the `componentWillUnmount`, and after some ajax req, `this.props.params.history.push('/url');`, the listen doesn't fire in this case – Mehdi Dehghani May 29 '19 at 05:43
  • @MehdiDehghani Why do you read history from params, shouldn't it be `this.props.history.push('/url')` – Shubham Khatri May 29 '19 at 05:46
  • @ShubhamKhatri good question, because of redux and its `mapStateToProps` and `mapDispatchToProps` I only have mapped items in the props object. the whole part in my prev comment happens in child component btw. I passed `params` via its parent (_which is stateless component_), e.g `` – Mehdi Dehghani May 29 '19 at 05:52
  • @ShubhamKhatri I just tried to use `withRouter` and `this.props.history.push('/url')`, still listen doesn't fire. – Mehdi Dehghani May 29 '19 at 06:00
  • @ShubhamKhatri Will it work if I change the url manually in the browser and press enter? – Souvik Ghosh Jun 21 '19 at 08:37
  • When I change URL by hand history.listen does not fire also. And I need this. – axell-brendow Mar 28 '20 at 12:40
  • Not working for me, I don't know why. The debugger never hit the event line. – mimic Dec 03 '20 at 22:18
61

Update for React Router 5.1+.

import React from 'react';
import { useLocation, Switch } from 'react-router-dom'; 

const App = () => {
  const location = useLocation();

  React.useEffect(() => {
    console.log('Location changed');
  }, [location]);

  return (
    <Switch>
      {/* Routes go here */}
    </Switch>
  );
};
onosendi
  • 724
  • 4
  • 10
23

react-router v6

In the upcoming v6, this can be done by combining the useLocation and useEffect hooks

import { useLocation } from 'react-router-dom';

const MyComponent = () => {
  const location = useLocation()

  React.useEffect(() => {
    // runs on location, i.e. route, change
    console.log('handle route change here', location)
  }, [location])
  ...
}

For convenient reuse, you can do this in a custom useLocationChange hook

// runs action(location) on location, i.e. route, change
const useLocationChange = (action) => {
  const location = useLocation()
  React.useEffect(() => { action(location) }, [location])
}

const MyComponent1 = () => {
  useLocationChange((location) => { 
    console.log('handle route change here', location) 
  })
  ...
}

const MyComponent2 = () => {
  useLocationChange((location) => { 
    console.log('and also here', location) 
  })
  ...
}

If you also need to see the previous route on change, you can combine with a usePrevious hook

const usePrevious = (value) => {
  const ref = React.useRef()
  React.useEffect(() => { ref.current = value })

  return ref.current
}

const useLocationChange = (action) => {
  const location = useLocation()
  const prevLocation = usePrevious(location)
  React.useEffect(() => { 
    action(location, prevLocation) 
  }, [location])
}

const MyComponent1 = () => {
  useLocationChange((location, prevLocation) => { 
    console.log('changed from', prevLocation, 'to', location) 
  })
  ...
}

It's important to note that all the above fire on the first client route being mounted, as well as subsequent changes. If that's a problem, use the latter example and check that a prevLocation exists before doing anything.

dwlz
  • 9,793
  • 6
  • 46
  • 76
davnicwil
  • 20,057
  • 9
  • 87
  • 98
  • I have a question. If several components have been rendered and they are all watching useLocation then all their useEffects will be triggered. How do I verify that this location is correct for the specific component that will be displayed? – Kex Jul 29 '20 at 16:50
  • 1
    Hey @Kex - just to clarify `location` here is the browser location, so it's the same in every component and always correct in that sense. If you use the hook in different components they'll all receive the same values when location changes. I guess what they do with that info will be different, but it's always consistent. – davnicwil Jul 29 '20 at 17:02
  • That makes sense. Just wondering how a component will know if the location change is relevant to itself performing an action. Eg a component receives dashboard/list but how does it know if it’s tied to that location or not? – Kex Jul 29 '20 at 17:08
  • Unless I do something like if (location.pathName === “dashboard/list”) { ..... actions }. It doesn’t seem very elegant hardcoding path to a component though. – Kex Jul 29 '20 at 17:12
  • Using the `useLocation`/`useEffect` method helped get past the "no change after first load" issue on single-page Ionic 5 React projects (using useParams). None of the Ionic Lifecycle methods were triggered after first load. – naaman May 16 '21 at 12:35
15

If you want to listen to the history object globally, you'll have to create it yourself and pass it to the Router. Then you can listen to it with its listen() method:

// Use Router from react-router, not BrowserRouter.
import { Router } from 'react-router';

// Create history object.
import createHistory from 'history/createBrowserHistory';
const history = createHistory();

// Listen to history changes.
// You can unlisten by calling the constant (`unlisten()`).
const unlisten = history.listen((location, action) => {
  console.log(action, location.pathname, location.state);
});

// Pass history to Router.
<Router history={history}>
   ...
</Router>

Even better if you create the history object as a module, so you can easily import it anywhere you may need it (e.g. import history from './history';

Fabian Schultz
  • 14,323
  • 4
  • 44
  • 51
10

This is an old question and I don't quite understand the business need of listening for route changes to push a route change; seems roundabout.

BUT if you ended up here because all you wanted was to update the 'page_path' on a react-router route change for google analytics / global site tag / something similar, here's a hook you can now use. I wrote it based on the accepted answer:

useTracking.js

import { useEffect } from 'react'
import { useHistory } from 'react-router-dom'

export const useTracking = (trackingId) => {
  const { listen } = useHistory()

  useEffect(() => {
    const unlisten = listen((location) => {
      // if you pasted the google snippet on your index.html
      // you've declared this function in the global
      if (!window.gtag) return

      window.gtag('config', trackingId, { page_path: location.pathname })
    })

    // remember, hooks that add listeners
    // should have cleanup to remove them
    return unlisten
  }, [trackingId, listen])
}

You should use this hook once in your app, somewhere near the top but still inside a router. I have it on an App.js that looks like this:

App.js

import * as React from 'react'
import { BrowserRouter, Route, Switch } from 'react-router-dom'

import Home from './Home/Home'
import About from './About/About'
// this is the file above
import { useTracking } from './useTracking'

export const App = () => {
  useTracking('UA-USE-YOURS-HERE')

  return (
    <Switch>
      <Route path="/about">
        <About />
      </Route>
      <Route path="/">
        <Home />
      </Route>
    </Switch>
  )
}

// I find it handy to have a named export of the App
// and then the default export which wraps it with
// all the providers I need.
// Mostly for testing purposes, but in this case,
// it allows us to use the hook above,
// since you may only use it when inside a Router
export default () => (
  <BrowserRouter>
    <App />
  </BrowserRouter>
)
  • i have tried your code but it can not detect when i change a route. it works when i refresh the page. but when is change route the useTracking() is not called again in app.js, is there a way i can make useTracking() get called again when a route changes ? – Eric. M Apr 22 '21 at 07:01
1

I came across this question as I was attempting to focus the ChromeVox screen reader to the top of the "screen" after navigating to a new screen in a React single page app. Basically trying to emulate what would happen if this page was loaded by following a link to a new server-rendered web page.

This solution doesn't require any listeners, it uses withRouter() and the componentDidUpdate() lifecycle method to trigger a click to focus ChromeVox on the desired element when navigating to a new url path.


Implementation

I created a "Screen" component which is wrapped around the react-router switch tag which contains all the apps screens.

<Screen>
  <Switch>
    ... add <Route> for each screen here...
  </Switch>
</Screen>

Screen.tsx Component

Note: This component uses React + TypeScript

import React from 'react'
import { RouteComponentProps, withRouter } from 'react-router'

class Screen extends React.Component<RouteComponentProps> {
  public screen = React.createRef<HTMLDivElement>()
  public componentDidUpdate = (prevProps: RouteComponentProps) => {
    if (this.props.location.pathname !== prevProps.location.pathname) {
      // Hack: setTimeout delays click until end of current
      // event loop to ensure new screen has mounted.
      window.setTimeout(() => {
        this.screen.current!.click()
      }, 0)
    }
  }
  public render() {
    return <div ref={this.screen}>{this.props.children}</div>
  }
}

export default withRouter(Screen)

I had tried using focus() instead of click(), but click causes ChromeVox to stop reading whatever it is currently reading and start again where I tell it to start.

Advanced note: In this solution, the navigation <nav> which inside the Screen component and rendered after the <main> content is visually positioned above the main using css order: -1;. So in pseudo code:

<Screen style={{ display: 'flex' }}>
  <main>
  <nav style={{ order: -1 }}>
<Screen>

If you have any thoughts, comments, or tips about this solution, please add a comment.

Beau Smith
  • 29,103
  • 12
  • 82
  • 88
1

React Router V5

If you want the pathName as a string ('/' or 'users'), you can use the following:

  // React Hooks: React Router DOM
  let history = useHistory();
  const location = useLocation();
  const pathName = location.pathname;
jefelewis
  • 769
  • 4
  • 24
1
import React from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import Sidebar from './Sidebar';
import Chat from './Chat';

<Router>
    <Sidebar />
        <Switch>
            <Route path="/rooms/:roomId" component={Chat}>
            </Route>
        </Switch>
</Router>

import { useHistory } from 'react-router-dom';
function SidebarChat(props) {
    **const history = useHistory();**
    var openChat = function (id) {
        **//To navigate**
        history.push("/rooms/" + id);
    }
}

**//To Detect the navigation change or param change**
import { useParams } from 'react-router-dom';
function Chat(props) {
    var { roomId } = useParams();
    var roomId = props.match.params.roomId;

    useEffect(() => {
       //Detect the paramter change
    }, [roomId])

    useEffect(() => {
       //Detect the location/url change
    }, [location])
}