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
I cloned your repo and noticed a couple different things going on:
react-router-dom
to the project itself vianpm i react-router-dom
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: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 bycreateRoutesFromElements
and the second argument should be an object with options (in your case,basename
).Here is a fixed
router
object: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 yourpackage.json
– you’ve probably installed is globally instead of inside the project. Runnpm install react-router-dom
inside this project’s directory to fix that.