Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically Navigate w/ HashRouter

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');
  ...
}
like image 412
Mike Avatar asked May 26 '17 23:05

Mike


People also ask

How do I programmatically navigate with react router?

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.

What is programmatic navigation?

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.


1 Answers

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.

like image 80
Tharaka Wijebandara Avatar answered Nov 04 '22 22:11

Tharaka Wijebandara