React Router not working with Github Pages
Asked Answered
Z

7

32

My previous website only shows the home page when the home tab is clicked, then if you click my navbar brand, it says 404. This website worked on a create-react-app with npm start, but it doesn't work here, nor on the build. I don't know what is wrong with the app, maybe the router setup is messed up, I don't know. I have linked the App and Index pages where I have the router setup. If you need any more information, just ask me for more information.

Thank You

Index

import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom'
import App from './App';
import './styles/index.css';

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>
);

App

import { Routes, Route } from "react-router-dom";
import Navbar from "./components/Navbar";
import About from "./routes/About";
import Contact from "./routes/Contact";
import Home from "./routes/Home";
import Project from "./routes/Project";

const App = () => {
  return (
    <>
      <Navbar />
      <Routes>
        <Route path="/" element={<Home />}></Route>
        <Route path="/about" element={<About />}></Route>
        <Route path="/project" element={<Project />}></Route>
        <Route path="/contact" element={<Contact />}></Route>
      </Routes>
    </>
  );
};

export default App;
Zizith answered 23/4, 2022 at 23:38 Comment(0)
A
64
  1. If deploying to GitHub, ensure there is a "homepage" entry in package.json for where you are hosting it in Github.

    Examples:

    User Page

    "homepage": "https://amodhakal.github.io",
    

    Project Page

    "homepage": "https://amodhakal.github.io/portfolio",
    

    Custom Domain Page

    "homepage": "https://amodhakal.com",
    
  2. Switch to the HashRouter since GitHub pages doesn't support the tech used by the BrowserRouter.

    index

    import React from 'react';
    import ReactDOM from 'react-dom/client';
    import { HashRouter } from 'react-router-dom';
    import App from './App';
    import './styles/index.css';
    
    ReactDOM.createRoot(document.getElementById('root')).render(
      <React.StrictMode>
        <HashRouter>
          <App />
        </HashRouter>
      </React.StrictMode>
    );
    

    [email protected]+ data routers

    import React from 'react';
    import ReactDOM from 'react-dom/client';
    import {
      createHashRouter,
      RouterProvider
    } from 'react-router-dom';
    import App from './App';
    import './styles/index.css';
    
    const router = createHashRouter([
      {
        path: "/*",
        element: <App />,
      }
    ]);
    
    ReactDOM.createRoot(document.getElementById('root')).render(
      <React.StrictMode>
        <RouterProvider router={router} />
      </React.StrictMode>
    );
    

For more details see the create-react-app docs for deploying to GitHub Pages and notes on client-side routing.

Adige answered 24/4, 2022 at 5:37 Comment(3)
Thank You, I added the Hash Router along with the changes to the homepage which I had had "homepage": "https://amodhakal.github.io/portfolio". I changed it and it is working, thank you!Zizith
"homepage": "./" is more universalStreit
@Streit I don't disagree that "." and "./" are more universal, but this answer is based on the suggestions for configuring running a React app on Github pages.Adige
P
15

I faced this similar routing problem in ReactJs when I used gh-pages.

My Problem: Routes are working fine at my local system but when I deployed my web app using gh-pages, I wasn't able to go to the sub-pages directly.

Example: ayushjaink8.github.io/cfhelper was working, and I am able to go to other pages from within the web app. But when I enter ayushjaink8.github.io/cfhelper/dashboard in the URL, it shows the github 404 error page.

Solution: I resolved the above problem by using <HashRouter/> and adding the homepage tag in the package.json like homepage: "/<repository-name>/#".

Note that gh-pages also follows the # rule in its URL routing. So it won't show any 404 error page if you write ayushjaink8.github.io/cfhelper/#/<any-route-of-your-app>.

Everything else remains the same in my codebase. I did not use the useHistory(), <BrowserRouter /> or any other functions. Only using <HashRouter/> works most of the time.

Your homepage becomes /<repo-name>/# instead of /<repo-name>. That's the only thing that change when you use <HashRouter/>.

For example, previously the homepage is: https://ayushjaink8.github.io/cfhelper/ with <HashRouter/>, the URL now becomes: https://ayushjaink8.github.io/cfhelper/#

This also applies to the routes.

Here goes my sample code:

import { Routes, Route, HashRouter } from "react-router-dom";

<HashRouter>
      <Navbar />
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/auth/login" element={<Login />} />
        <Route path="/auth/signup" element={<Signup />} />
        <Route path="/dashboard" element={<Dashboard />} />
        <Route path="/contests/create" element={<CreateContest />} />
        <Route exact path="/contests/join" element={<JoinContest />} />
        <Route path="/contests/live" element={<LiveContest />} />
        <Route path="/practice" element={ <Practice /> } />
        <Route path="/analyze" element={ <Analyze /> } />
        <Route path="/verify" element={<VerifyEmail />} />
        <Route path="/profile/edit" element={<EditProfile />} />
      </Routes>
      <Footer />
</HashRouter>

Package.json Sample Code:

{
  "name": "cfhelper",
  "homepage": "/<your-github-repo-name>/#",
  "version": "1.0.0",
  "private": true,
}
Parlous answered 21/10, 2022 at 6:3 Comment(0)
D
5

If you are using HashRouter, your anchors should look like the following format:

<a href="#/endpoint"></a>

instead of

<a href="/endpoint"></a>

And here is an example for the HashRouter:

<HashRouter>
    <Routes>
        <Route path="/" element={<HomePage />} />
        <Route path="/endpoint" element={<MyComponent />} />
        <Route path="*" element={<NotFoundPage />} />
    </Routes>
</HashRouter>

I realised this after spending so many hours. Hope this will help someone.

Dhobi answered 25/5, 2023 at 16:48 Comment(0)
S
2

I faced this problem in ReactJS when I used gh-pages.

My problem: Routes are working fine on my local system, but when I deployed my web app to gh-pages, it wasn't working.

Just like the other answers, first of all:

  1. Make sure there is a "homepage" entry in package.json for where you are hosting it on GitHub Pages.

Example:

 "homepage": "https://{username}.github.io/{repository-name}/",
  1. Switch BrowserRouter to HashRouter.

index.js

    import React from 'react';
    import ReactDOM from 'react-dom/client';
    import App from './App';
    import { HashRouter } from 'react-router-dom';

    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(
      <React.StrictMode>
        <HashRouter>
          <App />
       </HashRouter>
      </React.StrictMode>
    );

I was using the anchor element like this:

<a href="/">Home</a>
<a href="/about">About</a>

It was working on my local host, but in my GitHub page it gave me error 404: Page not found, there a two solutions that I found to this problem.

First solution: Change href attribute of the anchor elements to where you are hosting in GitHub pages.

For example:

<a href="https://{username}.github.io/{repository-name}/">Home</a>
<a href="https://{username}.github.io/{repository-name}/about">About</a>

This worked for me. But now you won't be able to test it on your localhost. However, if you want to stick with your anchor element or your Link element, this solution works.

Second solution: This is the one I found that works the best. Change the anchor elements or the Link elements to buttons, and add an onClick event to change pages using useNavigate.

App.js

import Home from './pages/Home';
import About from './pages/About';
import { Routes, Route, useNavigate } from 'react-router-dom';

function App() {
const navigate = useNavigate();

return 
<>
   <button onClick={() => navigate('/')}>Home</button>
   <button onClick={() => navigate('/about')}>About</button>
   <Routes>
     <Route path="/" element={ <Home/> } />
     <Route path="/about" element={ <About/> } />
   </Routes>
</>
 }

export default App;

Hope this helps.

Schmeltzer answered 24/6, 2023 at 5:58 Comment(0)
A
1

My 2cents.

  1. Add homepage in package.json, e.g.:
"homepage": "https://volodalexey.github.io/test_swapi_ant",
  1. Add different router types in your application. E.g. src/routes/router.tsx:
import React from 'react'
import {
  createHashRouter,
  createBrowserRouter,
  createRoutesFromElements,
  Route
} from 'react-router-dom'
import { HomeLayout } from '../layouts/HomeLayout'

const routes = createRoutesFromElements(
  <Route>
    <Route index element={<HomeLayout />}
  </Route>
)

export const router = process.env.HASH_ROUTER === 'true' ? createHashRouter(routes) : createBrowserRouter(routes)

Use this router, e.g. in src/App.tsx:

import React, { type ReactElement } from 'react'
import { RouterProvider } from 'react-router-dom'
import { router } from './routes/router'

function App (): ReactElement {
  return (
    <RouterProvider router={router} />
  )
}

export default App
  1. Use with webpack different HASH_ROUTER values. E.g. webpack.config.js:
const { DefinePlugin } = require('webpack')

module.exports = {
  ...
  plugins: [
    new DefinePlugin({
      'process.env.HASH_ROUTER': JSON.stringify(process.env.HASH_ROUTER || 'false')
    })
  ]
  ...
}
  1. Prepare different build scripts. E.g. history-router for resular usage (local or deployed to own server) and hash-router for github pages. e.g. in package.json:
  "scripts": {
    "build": "webpack",
    "build-github": "HASH_ROUTER=true webpack",
    "serve": "webpack serve"
  },
  1. Build for github pages npm run build-github and push to gh-pages branch (e.g. only dist folder in my case) git subtree push --prefix dist origin gh-pages.

See example in my repo https://github.com/volodalexey/test_swapi_ant

Ammonia answered 20/5, 2023 at 17:47 Comment(0)
B
0

// add basename to your browserRouter component

<BrowserRouter basename='/reponame'>
  <App/>
<BrowserRouter/>
Brahui answered 28/11, 2022 at 6:2 Comment(0)
S
-3

Figured it out. It's because of the url structure.

https://umair-mirza.github.io/safetyapp/

means you have to define a route for /safetyapp

like this:

<Route path='/safetyapp' element={<Home />} />
Sideshow answered 15/5, 2022 at 20:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.