Ad

Is It Possible To Match The # Part For Any Route In React Router 5?

In my app, I'd like to match all routs that end with #something.

   /map#login
   /info#login
and
   /map#register
   /map/one#register
   /info#register
   /info/two#register

So I can show component as popup on top of the content. How this can be done?

Ad

Answer

I found a solution for this case. It was inspired from this question in stackOverflow. Using HashRoute wrapper for Route and showing component based on location.hash.

const HashRoute = ({ component: Component, hash, ...routeProps }) => (
  <Route
    {...routeProps}
    component={({ location, ...props }) =>
      location.hash === hash && <Component {...props} />
    }
  />
);

export default class App extends Component {
  constructor() {
    super();
  }

  render() {
    return (
      <div className='App'>
        <Router history={history}>
            <HashRoute hash='#login'component={Login} />
            <HashRoute hash='#register' component={Register} />

            <Switch>
              <Route exact path='/map' component={Map} />
              <Route exact path='/info' component={Info} />
            </Switch>
        </Router>
      </div>
    );
  }
}

Ad
source: stackoverflow.com
Ad