React browserHistory.push giving Uncaught TypeError: Cannot read the "push" property from undefined

I am trying to change the page when clicked. Here is the click function

import React, { Component } from 'react'; import {BrowserRouter as Router,Route} from 'react-router-dom'; import { browserHistory } from 'react-router'; class Buttons extends Component { skipClick(){ browserHistory.push('/sessionstate2'); } render() { return (<a className={skipShow} onClick={this.skipClick}>Skip</a>) } } 

and index.js

 import browserHistory from 'react-router'; ReactDOM.render( <Router history={browserHistory}> <div> <Route exact path="/" component={App} /> <Route exact path="/sessionstate1" component={Template1}/> <Route exact path="/sessionstate2" component={Template2}/> <Route exact path="/sessionstate3" component={Template3}/> </div> </Router>, document.getElementById('root') ); 

He gives

Uncaught TypeError: Unable to read the "push" property from undefined

Could you tell me what I'm doing wrong here?

+1
javascript reactjs react-router
source share
2 answers

Here's a reproducible example of how to programmatically change routes in the v4 reply router.

First install the template for a simple application:

 sudo npm install -g create-react-app create-react-app demo-app cd demo-app npm install react-router-dom 

Then we change /src/App.js to:

 import React from 'react' import {BrowserRouter as Router, Route, Link, withRouter} from 'react-router-dom' const BasicExample = () => ( <Router> <div> <li><Link to="/">Home</Link></li> <li><Link to="/about">About</Link></li> <Route exact path="/" component={Home}/> <Route path="/about" component={About}/> </div> </Router> ) const Home = () => ( <div> <h2>Home</h2> </div> ) const Button = withRouter(({history}) => ( <button type='button' onClick={() => { history.push('/new-location') }}>Click Me!</button> )) const About = () => ( <div> <h2>About</h2> <Button /> </div> ) export default BasicExample 

Then start your server:

 npm run start 

If you go to localhost: 3000, and then click "About", you will see the button component. Clicking on it will programmatically change the route to /new-location

+3
source share

You no longer need to use browserHistory. React-router-dom enters the props and context of your route. One of these details is โ€œhistoryโ€, and this history object is a push function that you can call and pass the route to which you want to go.

in the base component of the class, you can create a function, as shown below, as an onClick handler to redirect to a specific link

 redirectToSessionStatePage() { this.props.history.push('/sessionstate2'); OR this.context.router.history.push('/sessionstate2'); } 

and in the component of the idle function

 redirectToSessionStatePage() { props.history.push('/sessionstate2'); OR context.router.history.push('/sessionstate2'); } 
0
source share

All Articles