SoFunction
Updated on 2025-04-07

react Route permissions Dynamic menu plan configuration react-router-auth-plus

text

Doing routing permission management in react has always been a troublesome thing, unlike vue that it has the function of intercepting before entering routes. I used a fool-configured routing permission library (based on react-router v6) during the fishing time.

react-router v6 document address

react-router-auth-plus github address

How to use

1. Configure routing

import { AuthRouterObject } from "react-router-auth-plus";
const routers: AuthRouterObject[] = [
  { path: "/", element: <Navigate to="/home" replace /> },
  { path: "/login", element: <Login /> },
  {
    element: <Layout />,
    children: [
      { path: "/home", element: <Home />, auth: ["admin"] },
      { path: "/setting", element: <Setting /> },
      {
        path: "/application",
        element: <Application />,
        auth: ["application"],
      },
    ],
  },
  { path: "*", element: <NotFound /> },
];

2. Render the route on the outermost layer of the application

Here I use swr to simulate getting permissions of the current user and return after two seconds.

// 
import { useAuthRouters } from "react-router-auth-plus";
const fetcher = async (url: string): Promise&lt;string[]&gt; =&gt;
  await new Promise((resolve) =&gt; {
    setTimeout(() =&gt; {
      resolve(["admin"]);
    }, 2000);
  });
function App() {
  const { data: auth, isValidating } = useSWR("/api/user", fetcher, {
    revalidateOnFocus: false,
  });
  return useAuthRouters({
    // The permissions of the current user, string[]    auth: auth || [],
    routers,
    // When jumping to a route without permission, the user will display it customly.  Here I display the 403 page.    noAuthElement: (router) =&gt; &lt;NotAuth /&gt;,
    // Render loading when the user permission has not been requested yet    render: (element) =&gt; (isValidating ? element : &lt;Loading /&gt;),
  });
}

Or you can use jsx to configure it

import { AuthRoute, createAuthRoutesFromChildren } from "react-router-auth-plus";
useAuthRouters({
    auth: auth || [],
    noAuthElement: (router) => <NotAuth />,
    render: (element) => (isValidating ? element : <Loading />),
    routers: createAuthRoutesFromChildren(
      <Routes>
        <AuthRoute path="/" element={<Navigate to="/home" replace />} />
        <AuthRoute path="/login" element={<Login />} />
        <AuthRoute element={<Layout />}>
          <AuthRoute path="/home" element={<Home />} auth={["admin"]} />
          <AuthRoute path="/setting" element={<Setting />} />
          <AuthRoute
            path="/application"
            element={<Application />}
            auth={["application"]}
          />
        </AuthRoute>
        <AuthRoute path="*" element={<NotFound />} />
      </Routes>
    ),
  });

This is done, isn't it a fool?

Permission Description

If the current home permission is set to["auth1", "auth2", "auth3"], as long as the current user's permissions meet one, it will be determined that they have the permissions for this route.

Dynamic menu

react-router-auth-plusChildren will be automatically passed to Layout, you do not have to pass them to Layout in the routing configuration. If you are ts, set the routers type to optional.

useAuthMenusIt will filter out routes without permissions. Next, you can process the data you want and then render it into antd Menu component.

import { useAuthMenus, AuthRouterObject } from "react-router-auth-plus";
interface LayoutProps {
  routers?: AuthRouterObject;
}
const Layout:FC<LayoutProps> = ({ routers }) => {
   const menus = useAuthMenus(routers);
   ...
}

The above is the detailed content of the react routing permission dynamic menu scheme to configure react-router-auth-plus. For more information about react routing permission dynamic menu, please follow my other related articles!