Skip to content

Instantly share code, notes, and snippets.

@israelalagbe
Created November 21, 2022 09:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save israelalagbe/1d49e14fa11d9f24b5ab8b2a5e5799c6 to your computer and use it in GitHub Desktop.
Save israelalagbe/1d49e14fa11d9f24b5ab8b2a5e5799c6 to your computer and use it in GitHub Desktop.
Code Splitting React
import { lazy } from 'react';
import { authGuard } from './guards/auth.guard';
import { paths } from './paths';
export const routes = [
{
path: paths.LANDING, page: lazy(() => import('../pages/landing/Landing.page')), guards: [], props: {},
},
{
path: paths.AUTH, page: lazy(() => import('../pages/auth/Auth.page')), guards: [], props: {},
},
{
path: paths.HOME, page: lazy(() => import('../pages/landing/Landing.page')), guards: [authGuard],
},
{
path: paths.FORGOTPASSWORD, page: lazy(() => import('../pages/forgot-password/ForgotPassword.page')),
},
{
path: paths.RESETPASSWORD, page: lazy(() => import('../pages/reset-password/ResetPassword.page')),
},
{ path: paths.REDIRECT, page: lazy(() => import('../pages/_3xx/R3xx.page')) },
{
page: lazy(() => import('../pages/_404/E404.page')),
},
];
import React, { Suspense, useContext } from 'react';
import {
BrowserRouter as Router,
Switch,
Route,
} from 'react-router-dom';
import { routes } from './routes';
import Loading from './RouteLoading.component';
import Guarded from './guards/Guard.component';
import AppContext from '../App.context';
import Snack from '../components/snack/Snack.component';
const Routing = () => {
const appContext = useContext(AppContext);
const { toaster } = appContext;
return (
<>
<Router>
<Suspense fallback={<Loading />}>
<Switch>
{
routes.map(
(route) => (
<Route
key={route.path || '404'}
path={route.path}
{...(route.props || {})}
exact
render={(props) => (
route.guards
? <Guarded route={route} {...(props || {})} {...(appContext || {})} />
: <route.page {...(props || {})} {...(appContext || {})} />
)}
/>
),
)
}
</Switch>
</Suspense>
</Router>
{
toaster?.messages?.length > 0
? <Snack toasted={toaster.pop()} />
: null
}
</>
);
};
export default Routing;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment