react-router v4 - browserHistory is undefined

demonofthemist picture demonofthemist · May 6, 2017 · Viewed 38.9k times · Source

I am creating my first react app in electron (my first electron app too). I have two routes & need to navigate from one to another. For that I am using following code:

Root

ReactDOM.render(
  <Router history={browserHistory}>
      <App />
  </Router>,
  document.getElementById('root')
);

App

class App extends React.Component {
    constructor() {
        super();
    }
    render() {
        return (
            <div className="app-master">
                <Switch>
                    <Route path='/city' component={CityList}/>
                    <Route path='/' component={SplashScreen}/>
                </Switch>
            </div>
        )
    }
}

Page

import { browserHistory } from 'react-router';
...
browserHistory.push('/city');

This line gives error,

TypeError: Cannot read property 'push' of undefined

I searched web for possible solution but can't find one! There are many similar questions on SO too, but none of it worked for me :(

Answer

Balthazar picture Balthazar · May 6, 2017

You have to import it from the history module now which provides 3 different methods to create different histories.

  • createBrowserHistory is for use in modern web browsers that support the history API
  • createMemoryHistory is used as a reference implementation and may also be used in non-DOM environments, like React Native or tests
  • createHashHistory for legacy web browsers

You cannot use the browser history in an electron environment, use the hash or the memory one.

import { createHashHistory } from 'history'

const history = createHashHistory()

You can then use the history injected in the props

this.props.history.push('/')