I was originally using hashHistory
from react-router
and programmatically navigating my React app using this.props.history.push()
. But with the move to using HashRouter
from the react-router-dom
package, this.props.history.push()
now throws a Cannot read property 'push' of undefined
error.
How do I programmatically navigate using HashRouter
now?
ReactDOM.render(
<Provider store={store}>
<MuiThemeProvider>
<HashRouter>
<div>
<Route exact path="/" component={App} />
<Route path="/landing" component={Landing} />
</div>
</HashRouter>
</MuiThemeProvider>
</Provider>,
document.getElementById('root'));
Render func of App.js
render() {
return (
<div className="App">
...
<div>
<Collapse isOpened={this.state.activeForm === 1}>
<SignUpForm />
</Collapse>
<Collapse isOpened={this.state.activeForm === 2}>
<SignInForm />
</Collapse>
...
</div>
);
}
Function in SignUpForm.js that's calling .push()
handleSubmit(e) {
...
this.props.history.push('/landing');
...
}
There are two ways to programmatically navigate with React Router - <Navigate /> and navigate() . You can get access to Navigate by importing it from the react-router-dom package and you can get access to navigate by using the custom useNavigate Hook.
Programmatic Navigation refers to when a user is redirected as a result of an action that occurs on a route. A login or signup action or form submission action on a route is a typical example of navigating programmatically.
If your component is rendered from a Route (like App and Landing), then you will have access to all router related props (match
, history
, location
). However, since SignUpForm isn't rendered with a Route, you won't have access to those props by default.
But we can use withRoute
higher-order component to explicitly get those props. We just need to wrap the component with this HoC before exporting it as follows.
export default withRouter(SignUpForm);
Now it will work as expected since SignUpForm gets history
prop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With