Reputation: 12316
I'm new in react and I'm trying to do a simple page with logged section, to do that I've integrated Auth0 like this (https://github.com/auth0-samples/auth0-react-samples/blob/master/01-Login).
My problem comes when I'm trying to use PrivateRoute, currently my routes are being done like this
app.js does renderRoutes and receives the routes array. My doubt is: How do I apply the PrivateRoutes to apply to all my dashboard components?
const routes = [
{
path: '/',
exact: true,
component: () => <Redirect to="/app" />,
},
{
path: '/auth',
component: AuthLayout,
routes: [
{
path: '/auth/login',
exact: true,
component: lazy(() => import('views/Login')),
},
{
component: () => <Redirect to="/errors/error-404" />,
},
],
},
{
route: '/app',
component: DashboardLayout,
routes: [
{
path: '/calendar',
exact: true,
component: lazy(() => import('views/Calendar'))
},
{
component: () => <Redirect to="/errors/error-404" />,
},
],
},
{
path: '/errors',
component: ErrorLayout,
routes: [
{
path: '/errors/error-401',
exact: true,
component: lazy(() => import('views/Error401')),
},
{
path: '/errors/error-404',
exact: true,
component: lazy(() => import('views/Error404')),
},
{
path: '/errors/error-500',
exact: true,
component: lazy(() => import('views/Error500')),
},
{
component: () => <Redirect to="/errors/error-404" />,
},
],
},
];
const Dashboard = props => {
const { route } = props;
const classes = useStyles();
const [openNavBarMobile, setOpenNavBarMobile] = useState(false);
const handleNavBarMobileOpen = () => {
setOpenNavBarMobile(true);
};
const handleNavBarMobileClose = () => {
setOpenNavBarMobile(false);
};
return (
<div className={classes.root}>
<TopBar
className={classes.topBar}
onOpenNavBarMobile={handleNavBarMobileOpen}
/>
<div className={classes.container}>
<NavBar
className={classes.navBar}
onMobileClose={handleNavBarMobileClose}
openMobile={openNavBarMobile}
/>
<main className={classes.content}>
<Suspense fallback={<LinearProgress />}>
{renderRoutes(route.routes)}
</Suspense>
</main>
</div>
<ChatBar />
</div>
);
};
const { loading } = useAuth0();
if (loading) {
return <h1>loading</h1>
}
return (
<StoreProvider store={store}>
<ThemeProvider theme={theme}>
<MuiPickersUtilsProvider utils={MomentUtils}>
<Router history={history}>
<ScrollReset />
<GoogleAnalytics />
<CookiesNotification />
{renderRoutes(routes)}
</Router>
</MuiPickersUtilsProvider>
</ThemeProvider>
</StoreProvider>
);
};```
Upvotes: 1
Views: 259
Reputation: 570
I used the same template that you're using before.
I implemented private routing like this.
Under AuthLayout component, if it's logged in already, I redirect to dashboard component
Under DashboardLayout, if it's not logged in, I redirect to '/auth'
Upvotes: 2