0
votes

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.
1
Instead of always returning a PrivateRoute, return route.authenticate ? <PrivateRoute ... /> : <Route /> - Chris G
Conditionally render Route or PrivateRoute within the map callback based on the authenticate value. Alternatively create a more general route component that consumes an auth prop and does the conditional rendering. Please try to update your question to include a Minimal, Complete, and Reproducible Example. - Drew Reese
Btw you should be careful! The field "authenticated" is expecting information whether a user is currently logged in, not if the route is private or not. Pass true if a user is authenticated and false if not to that prop instead. - Rajoe

1 Answers

0
votes

You can check the condition in private route and if they didn't satisfy the condition you can use useHistory hook to send them to 404 or some other route.

for doing this you need to create a context that wraps around your application and helps you to use the data around the application. you can use native react features but you can also use redux which is my go to and you can use redux for your state management.

the code in the page will be like this:

const history = useHistory();
if ({condistion}) {
    history.push({valid_route});
}