skip to Main Content

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;

2

Answers


  1. 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",
      }
    );
    
    Login or Signup to reply.
  2. the problem is that you’re using createBrowserRouter incorrectly. According to the documentation, there should be two arguments – the first one should be an array of routes (in your case, returned by createRoutesFromElements and the second argument should be an object with options (in your case, basename).

    Here is a fixed router object:

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

    To avoid such errors in the future, I recommend using TypeScript – in this case, TypeScript should be able to detect that the types of the arguments are incorrect and point you to the solution.

    Also, react-router-dom is missing from the dependencies in your package.json – you’ve probably installed is globally instead of inside the project. Run npm install react-router-dom inside this project’s directory to fix that.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search