Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

javascript - 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.
question from:https://stackoverflow.com/questions/65898281/conditional-rendering-in-react-router-with-private-and-public-routes

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...