0

How can I make routing in React, using react-router-dom, using hashbang? Something like

http://somesite.com/#/home

http://somesite.com/#/about

is fine by me.

In Angular routing, I used { useHash: true } in RouterModule of angular/router to achieve that.

In Vue routing, I used history: createWebHashHistory() in createRouter method of vue-router to achieve that.

Is there a way I achieve that here?

If it's not - please suggest me some other solid routing libraries for React.

P.S. If you wonder why I need it, the answer is IIS. And I don't want to go through overcomplicated procedure of getting it to work on IIS.

Dalibor
  • 1,430
  • 18
  • 42

2 Answers2

2

You need to use a HashRouter: https://reactrouter.com/web/api/HashRouter

For example, you can do the following:

import { HashRouter as Router, Route, Switch } from 'react-router-dom';

const App = () => {
  return (
    <Router>
      <Switch>
        <Route exact path="/foo">
          <Component1/>
        </Route>
        <Route exact path="/bar">
          <Component2/>
        </Route>
      </Switch>
    </Router>);
}
Abhyudaya Sharma
  • 1,173
  • 12
  • 18
  • Thank you. However, how do I use props.match, props.location, props.history... on the pages that are routed? It throws error now that I tried this "Cannot read property 'url' of undefined", whether I tried it on development server or on IIS – Dalibor Dec 25 '20 at 12:01
  • @Dalibor You need to use `withRouter`. This will help: https://stackoverflow.com/a/56622289/6306974 – Abhyudaya Sharma Dec 25 '20 at 12:10
  • Sorry, sorry... It works fine.. I used "this.props.history.push" instead of "props.history.push" as I used it before I tried HashRouter. It's working fine now, it was not withRouter issue; I understand I need to use withRouter in components in a routed page, but this was another issue. Thanks! – Dalibor Dec 25 '20 at 12:13
1

Use <HashRouter> instead of one of the other routers.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335