Github pages HashRouter not displaying components

Viewed 502

My react app on github page doesn't render the components using HashRouter, blank page on "/" and 404 error on "/about". this is my app.js

function App() {
  return (
    <div className="Container-fluid" id="div2">
      <HashRouter basename="/Landing-Page">
        <Header />

        <Routes>
          <Route path="/thankyou" element={<ThankYou />} />
          <Route
            exact
            path="/"
            element={
              <div className="Container">
                <SignUp validate={validate} />
                <EbookInfo />
              </div>
            }
          />
          <Route path="/about" element={<About />} />
        </Routes>
      </HashRouter>
    </div>
  );
}

on homepage it shows .../Landing-Page/ as expected but on other page it shows .../about instead of .../Landing-Page/about. I have gh-pages setup. my github page https://alexhmar.github.io/Landing-Page/ my repo https://github.com/alexhmar/Landing-Page/tree/master

I have also tried this with <Router basename={process.env.PUBLIC_URL} but it's the same issue.

2 Answers

When using Github Pages and React Router Dom you need to use the Hash Router.

Replace your import by import { HashRouter as Router } from "react-router-dom"; and it should work.

Github Pages isn't configured for single page applications, if you try to access /bar, it will try to find a bar.html file and thus give you a 404. By using the hash router, when you navigate to links it will go to /#bar so Github Pages won't redirect you and React Router Dom will see it as navigating to /bar as you'd expect it, as long as you're using the Link component or the hooks.

I deployed on Heroku instead of Github pages,now it's working fine.

Related