Michel H.
Michel H.

Reputation: 300

React Router v4 on change

I am developing an ordinary React JS app and using a BrowserRouter. I need to know when the route changes and the only thing I found was to use the history package by the same guys (react-training).

Their example looks easy enough but does not work at all for me:

import createHistory from 'history/createBrowserHistory'
const history = createHistory()

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


const A = props => <div>A <NavLink to="/b">b</NavLink></div>
const B = props => <div>B <NavLink to="/a">a</NavLink></div>

ReactDOM.render(
    <BrowserRouter>
        <div>
            <Route path="/a" component={A}/>
            <Route path="/b" component={B}/>
        </div>
    </BrowserRouter>,
    document.getElementById('app')
)

The console prints "a" but the listen-callback never gets called when I click around and my URL changes.

There is not much more in their documentation so does anyone know what is missing?

Upvotes: 3

Views: 1935

Answers (1)

sehrob
sehrob

Reputation: 1044

If you want to listen route changes in this way, I think you should use Router not BrowserRouter and give it your new created history as a prop.

Here is the code with changes:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link } from 'react-router-dom';
import createHistory from 'history/createBrowserHistory'

const history = createHistory()

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


const A = props => <div>A <Link to="/b">b</Link></div>
const B = props => <div>B <Link to="/a">a</Link></div>

ReactDOM.render(
  <Router history={history}>
    <div>
        <div>Hello!</div>
        <Route path="/a" component={A}/>
        <Route path="/b" component={B}/>
    </div>
  </Router>,
  document.getElementById('root')
)

And here is the console log that I got:

enter image description here

Hope it helps.

Upvotes: 8

Related Questions