How can I render a component based on auth props? For example, I have a routes.js file that contains all of my routes including private and public routes.
I want to have a single route file that contains all the routes whether it is a private or public component because the home.js will check these later on.
Below is my route files that contain the routes:
import { Login, Register } from 'pages/form/components/';
import SecuredRoute from 'components/SecuredRoute';
const routes = [
{
path: '/',
authenticate: false,
component: Login
},
{
path: '/signup',
authenticate: false,
component: Register
},
{
path: '/secured1',
authenticate: true,
component: SecuredRoute
},
{
path: '/secured2',
authenticate: true,
component: SecuredRoute
}
];
export default routes;
and below is my snippet in Home.js file the renders the component.
<Switch>
{routes.map((route, index) => {
return (
<PrivateRoute
exact
authenticated={route.authenticate}
path={route.path}
component={route.component}
key={index}
/>
);
})}
</Switch>
As of the moment, I can only render the private component but not the public routes Question:
- How can I check if the routes are public or private inside a map function? As you can see in the snippet, it renders only the private but not the public component.
route.authenticate ? <PrivateRoute ... /> : <Route />- Chris GRouteorPrivateRoutewithin the map callback based on theauthenticatevalue. Alternatively create a more general route component that consumes anauthprop and does the conditional rendering. Please try to update your question to include a Minimal, Complete, and Reproducible Example. - Drew Reese