Uncaught TypeError: Cannot read property 'push' of undefined (React-Router-Dom)
Solution 1:
In order to make use of history
in the App
component use it with withRouter
. You need to make use of withRouter
only when your component is not receiving the Router props
,
This may happen in cases when your component is a nested child of a component rendered by the Router or you haven't passed the Router props to it or when the component is not linked to the Router at all and is rendered as a separate component from the Routes.
import React from 'react';
import { Route , withRouter} from 'react-router-dom';
import Dashboard from './Dashboard';
import Bldgs from './Bldgs';
var selectedTab;
class App extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
selectedTab = 0;
}
handleClick(value) {
selectedTab = value;
// console.log(selectedTab);
this.props.history.push('/Bldgs');
// console.log(this.props);
}
render() {
var _this = this;
return (
<div>
<Route exact path="/" render={(props) => <Dashboard {...props} handleClick={_this.handleClick} />} />
<Route path="/Bldgs" component={Bldgs} curTab={selectedTab} />
</div>
);
}
}
export default withRouter(App);
Documentation on withRouter
Solution 2:
for React-router V4 change the function to
onClick={this.fun.bind(this)}
fun() {
this.props.history.push("/Home");
}
and
import { withRouter } from 'react-router-dom';
export it later as:
export default withRouter (comp_name);
Solution 3:
When working with functional components we can use useHistory() to history to push method
import { useHistory } from "react-router-dom";
and then in function we have to assign the useHistory()
let history = useHistory();
Now We can use history.push to relocate to desired page
history.push('/asdfg')