I need help with integrating nested routes into my app. Can someone guide me on how to add nested routes?
Here is the structure of my app:
import { Route, Routes } from 'react-router-dom';
import routes, { RouteModel } from './router/routes';
import CustomRoute from './router/CustomRoute';
const renderRoutes = (routes: RouteModel[]) => {
return routes.map((route, index) => {
if (route.SubItems && route.SubItems.length > 0) {
return (
<Route
key={index}
path={route.Path}
element={
<CustomRoute path={route.Path}>
<route.Page />
{renderRoutes(route.SubItems)}
</CustomRoute>
}
/>
);
} else {
return (
<Route
key={index}
path={route.Path}
element={
<CustomRoute path={route.Path}>
<route.Page />
</CustomRoute>
}
/>
);
}
});
};
const App = () => {
return <Routes>{renderRoutes(routes)}</Routes>;
};
export default App;
My defined routes are as follows:
import { ComponentType } from 'react';
import CreateCarPage from '../page/car/create/page';
import HomePage from '../page/home/page';
import LoginPage from '../page/login/page';
import ListCarPage from '../page/car/list/page';
export type RouteModel = {
Path: string;
Page: ComponentType<any>;
Text: string;
SubItems?: RouteModel[];
};
const routes: RouteModel[] = [
{
Path: '*',
Page: HomePage,
Text: 'Home',
},
{
Path: '/login',
Page: LoginPage,
Text: 'Login',
},
{
Path: '/car',
Page: ListCarPage,
Text: 'Car',
SubItems: [
{
Path: '/car/create',
Text: 'Create',
Page: CreateCarPage,
},
],
},
];
export default routes;
Below is the implementation of my customRoute:
import { Navigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import Layout from '../component/layout/Layout';
type Props = {
children: React.ReactNode;
path: string;
};
const CustomRoute = ({ children, path }: Props) => {
const { authenticated } = useAuth();
if (path === '/login') {
return authenticated ? <Navigate to="/" /> : children;
}
return authenticated ? <Layout>{children}</Layout> : <Navigate to="/login" />;
};
export default CustomRoute;
The error I'm encountering:
Uncaught error: a
<Route>
is only ever to be used as the child of<Routes>
element, never rendered directly. Please wrap your<Route>
in a<Routes>