Search code examples
react-routerreact-router-dom

Navigate with useRoutes hook


I am using useRoutes hook within my project as the setup is as follows :

routes.js

const routes: RouteObject[] = [
  {
    path: "/",
    element: <AppLayout />,
    children: [
      { path: "", element: <HomePage /> },
      { path: "/login", element: <Login /> },
    ],
  },
];

function AppRoutes() {
  const router = useRoutes(routes);

  return router;
}

and then in App.tsx the code is as follows:

export default class App extends React.Component {
  render() {
    return (
      <Provider store={store}>
        <BrowserRouter>
          <ThemeProvider theme={theme}>
            <AppRoutes />
          </ThemeProvider>
        </BrowserRouter>
      </Provider>
    );
  }
}

My concern is as soon as i go to the base url for example localhost:3000, i see my AppLayout content being rendered, but not the Homepage, same goes for localhost:3000/login , I see the AppLayout not the Login component content being rendered and it says

Cannot GET /login

GEThttp://localhost:3000/login [HTTP/1.1 404 Not Found 7ms]


Solution

  • That is because you are defining your routes as children of the "main" route. By doing so, you are fining nested routes, which can be rendered inside of the "main" route component. To do so, use the Outlet component, in your AppLayout component (more info there).

    Another solution would simply be to define your routes directly inside the array (as "main" routes, not children), but you would have to apply the layout differently.