Created
November 19, 2020 15:03
-
-
Save ever-dev/54aa6a83714825490c83bc1c8fdac25f to your computer and use it in GitHub Desktop.
Render React routes with layouts and guards
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { | |
Suspense, | |
Fragment, | |
lazy | |
} from 'react'; | |
import { | |
Switch, | |
Redirect, | |
Route | |
} from 'react-router-dom'; | |
/** | |
* Load Layouts and Guards | |
*/ | |
export const renderRoutes = (routes = []) => ( | |
<Suspense fallback={<LoadingScreen />}> | |
<Switch> | |
{routes.map((route, i) => { | |
const Guard = route.guard || Fragment; | |
const Layout = route.layout || Fragment; | |
const Component = route.component; | |
return ( | |
<Route | |
key={i} | |
path={route.path} | |
exact={route.exact} | |
render={(props) => ( | |
<Guard> | |
<Layout> | |
{route.routes | |
? renderRoutes(route.routes) | |
: <Component {...props} />} | |
</Layout> | |
</Guard> | |
)} | |
/> | |
); | |
})} | |
</Switch> | |
</Suspense> | |
); | |
const routes = [ | |
{ | |
exact: true, | |
path: '/404', | |
component: lazy(() => import('src/views/errors/NotFoundView')) | |
}, | |
{ | |
exact: true, | |
guard: GuestGuard, | |
path: '/login', | |
component: lazy(() => import('src/views/auth/LoginView')) | |
}, | |
{ | |
path: '/app', | |
guard: AuthGuard, | |
layout: DashboardLayout, | |
routes: [ | |
{ | |
exact: true, | |
path: '/app/dashboard', | |
component: lazy(() => import('src/views/DashboardView')) | |
}, | |
{ | |
component: () => <Redirect to="/404" /> | |
} | |
] | |
}, | |
{ | |
path: '/docs', | |
layout: DocsLayout, | |
routes: [ | |
{ | |
exact: true, | |
path: '/docs', | |
component: () => <Redirect to="/docs/welcome" /> | |
}, | |
{ | |
exact: true, | |
path: '/docs/welcome', | |
component: lazy(() => import('src/views/docs/WelcomeView')) | |
}, | |
{ | |
component: () => <Redirect to="/404" /> | |
} | |
] | |
}, | |
{ | |
path: '*', | |
layout: MainLayout, | |
routes: [ | |
{ | |
exact: true, | |
path: '/', | |
component: HomeView | |
}, | |
{ | |
component: () => <Redirect to="/404" /> | |
} | |
] | |
} | |
]; | |
export default routes; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment