Sometimes, we’ll encounter the ‘ Cannot Read Property ‘push’ of undefined With React Router’ error in our React components.
In this article, we’ll look at how to fix the ‘ Cannot Read Property ‘push’ of undefined With React Router’ error in our React components.
Fix the Cannot Read Property ‘push’ of undefined With React Router Error
We can use the withRouter
higher-order component to make the history
object available.
For instance, we can write:
class App extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(value) {
this.props.history.push('/dashboard');
}
render() {
return (
<div>
<Route
exact
path="/"
render={() => (
<div>
<h1>Welcome</h1>
</div>
)}
/>
<Route
path="/dashboard"
render={() => (
<div>
<h1>Dashboard</h1>
</div>
)}
/>
<button onClick={this.handleClick} >go to dashboard</button>
);
}
}
export default withRouter(App);
We have several routes and a handleClick
method to let us go to the dashboard route.
We have the this.props.history.push
method because we called withRouter
higher-order component with App
.
Conclusion
We can use the withRouter
higher-order component to make the history
object available.