1

I have a requirement to include both BrowserRouter and HashRouter for different routes.

For this I have written this basic code to understand combining both:

    import React from "react";
    import {
    BrowserRouter as Router,
    Switch,
    Route,
    Link,
    HashRouter
    } from "react-router-dom";
    export default function BasicExample() {
  return (
   <Router>
  <div>
    <ul>
      <li>
        <Link to="/">Home</Link>
      </li>
      <li>
        <Link to="/about">About</Link>
      </li>
      <li>
        <Link to="/dashboard">Dashboard</Link>
      </li>
    </ul>
    <Switch>
      <Route exact path="/">
        <Home />
      </Route>
      <Route exact path="/about">
        <HashRouter>
           <Route path="/about" >
             <About />
            </Route> 
        </HashRouter>
      </Route>
       <Route path="/dashboard">
        <Dashboard />
      </Route>
    </Switch>
    </div>
    </Router>
   );
  }

This is the Home component

 function Home() {
 return (
 <div>
  <h2>Home</h2>
  </div>
 );
 }

This is the About component which has HashRouter

 function About() {
   return (
 <div>
  <h2>About</h2>
 </div>
 );
 }

This is again a normal component with BrowserRouter

 function Dashboard() {
  return (
  <div>
  <h2>Dashboard</h2>
  </div>
  );
  }

And when I click on the About link then it changes the URL but does not display the "About" text.

Learner
  • 99
  • 6
  • You should use one Router, not both. Why are you trying both? – Ajeet Shah Apr 13 '21 at 11:46
  • yes i understand, requirement is quite complicated. Is it possible or not? – Learner Apr 13 '21 at 20:22
  • Let me try to explain: My app is deployed in S3 as static site hosting. And when I am trying to access deep link url such as http://myapp/oder/status?query=12345 via cloudfront then I am getting 403 when using BrowserRouter. But when using HashRouter then it is fine. As we have other route in our app which follows BrowserRouter, so i want to combine both. Also redirecting 403 in S3 to index.html is not possible solution for us because of other security issue. – Learner Apr 13 '21 at 20:39
  • Related https://stackoverflow.com/questions/51974369/what-is-the-difference-between-hashrouter-and-browserrouter-in-react – Michael Freidgeim Jul 02 '23 at 03:12

0 Answers0