Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-router v4 - browserHistory is undefined

Tags:

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 :(

like image 242
demonofthemist Avatar asked May 06 '17 16:05

demonofthemist


People also ask

What is browserHistory react router?

React Router uses the history package, which builds on the browser history API to provide an interface to which we can use easily in React apps. location - (object) The current location. May have the following properties: pathname - (string) The path of the URL.

How do you use .push history in react?

push() Method. history. push() is another approach where we make use of the history props React Router provides while rendering a component. In other words, this works when the component is being rendered by React Router, bypassing the component as a Component prop to a Route.


1 Answers

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('/')
like image 118
Preview Avatar answered Oct 11 '22 06:10

Preview