Search code examples
reactjsreact-routerreact-router-dombrowser-history

How can I simulate same behavior as history.push("/Initial"); using hash router?


I had to modify from:

   <Provider store={store}>
        <I18nextProvider i18n={i18n}>
          <BrowserRouter>
            <Header />
            <Main />
            <Footer />
          </BrowserRouter>
        </I18nextProvider>
      </Provider>

to:

  <Provider store={store}>
            <I18nextProvider i18n={i18n}>
              <HashRouter>
                <Header />
                <Main />
                <Footer />
              </HashRouter>
            </I18nextProvider>
          </Provider>

I made the change to avoid 404 error when refreshing the page, and to avoid the same error when an activation url is sent from an email

Now, the code below does not work

history.push("/Drawer");

How I can do the same thing but using hashrouter


Solution

  • Try this:

    // install react-router-dom
    npm i react-router-dom
    
    // import withRouter in your Component
    import { withRouter } from 'react-router-dom';
    
    // now you can use
    // in class component
    this.props.history.push('/Drawer');
    // in function component
    props.history.push('/Drawer');
    
    // export your component
    // without connect
    export default withRouter(YourComponent);
    // with connect
    export default withRouter(connect(mapStateToProps, mapDispatchToProps)(YourComponent));