Search code examples
reactjsreact-routergithub-pages

React Application Serving 404 Component Instead of Index on Both Local and GitHub Pages


I am working on a React application and facing an issue where the application is showing the 404 error component instead of the index component. This is happening both on my local development server as well as when the application is deployed to GitHub Pages.

My code is available on GitHub: arch-studio-multipage-website repository.

Here is my routing setup in App.js:

import { createBrowserRouter, Route, createRoutesFromElements, RouterProvider } from "react-router-dom";
import RootLayout from "./layout/RootLayout";
import Home from "./pages/Home";
import NotFound from "./pages/NotFound";

const router = createBrowserRouter({
  basename: '/arch-studio-multipage-website',
  routes: createRoutesFromElements(
    <Route path="/" element={<RootLayout />}>
      <Route index element={<Home />} />
      <Route path="*" element={<NotFound />} />
    </Route>
  )
});

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

export default App;

Solution

  • I cloned your repo and noticed a couple different things going on:

    1. You need to install react-router-dom to the project itself via npm i react-router-dom
    2. You're passing arguments to createBrowserRouter incorrectly. It takes a list of routes as the first parameter and options second. I was able to get it working correctly by changing it to this:
    const router = createBrowserRouter(
      createRoutesFromElements(
        <Route path="/" element={<RootLayout />}>
          <Route index element={<Home />} />
          <Route path="*" element={<NotFound />} />
        </Route>
      ),
      {
        basename: "/arch-studio-multipage-website",
      }
    );