简体   繁体   中英

Conditional rendering in React Router with Private and Public Routes

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.

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});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM