简体   繁体   中英

page permission check with react router v6

I'm using useRoutes of React Router v6 to render routes, and I want to check permissions every time user access the page.

I found below example,but is there any other way to use a wrapper for each page? like next middleware.

https://stackblitz.com/github/remix-run/react-router/tree/main/examples/auth?file=src/App.tsx

about useRoutes: https://reactrouter.com/docs/en/v6/examples/route-objects

this is my code. it works but the problem is that NavBar is also invisible when an unauthorized user approaches.

function App() {
...
  const routes: RouteObject[] = [
    {
      path: "/",
      element: <RequireAuth role={"role test"} component={<NavBar />}></RequireAuth>,
      children: [
        { index: true, element: <Home /> },
        {
          path: "/pricing",
          element: <Pricing />,
        },
        {
          path: "/guide",
          element: <Guide />,
        },
        {
          path: "/consult",
          element: <Consult />,
        },
        { path: "*", element:  <Error /> }
      ]
    }
  ];
  let element = useRoutes(routes);
  
  return (
    <Fragment>
      <GlobalStyle />
      <ThemeProvider theme={theme}>
        {element}
      </ThemeProvider>
    </Fragment>
  );

...the problem is that NavBar is also invisible when an unauthorized user approaches.

Move the Navbar component outside the routes configuration so it is always rendered regardless of route or auth status.

const routes: RouteObject[] = [
  {
    path: "/",
    element: <RequireAuth role={"role test"} />,
    children: [
      { index: true, element: <Home /> },
      {
        path: "/pricing",
        element: <Pricing />,
      },
      {
        path: "/guide",
        element: <Guide />,
      },
      {
        path: "/consult",
        element: <Consult />,
      },
      { path: "*", element:  <Error /> }
    ]
  }
];

function App() {
  ...

  const element = useRoutes(routes);
  
  return (
    <Fragment>
      <GlobalStyle />
      <ThemeProvider theme={theme}>
        <NavBar /> // <-- render NavBar outside routes
        {element}
      </ThemeProvider>
    </Fragment>
  );
}

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