DEV Community

linxianxi
linxianxi

Posted on

Simpleton configuration! React Route permission and dynamic menu scheme - react-router-auth-plus

Introduce

Make you easy to use permission management based on react-router v6.
github

How to use

1. config routers

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 /> },
];
Enter fullscreen mode Exit fullscreen mode

2. render routers in App.tsx

Here I use SWR to simulate getting the privileges of the current user and returning two seconds later.

// App.tsx
import { useAuthRouters } from "react-router-auth-plus";

const fetcher = async (url: string): Promise<string[]> =>
  await new Promise((resolve) => {
    setTimeout(() => {
      resolve(["admin"]);
    }, 2000);
  });

function App() {
  const { data: auth, isValidating } = useSWR("/api/user", fetcher, {
    revalidateOnFocus: false,
  });

  return useAuthRouters({
    // current user auth,string[]
    auth: auth || [],
    routers,
    // 跳转到没权限的路由时,用户自定义显示。这里我显示 403 页面。
    noAuthElement: (router) => <NotAuth />,
    // 用户权限还没请求到时,渲染 loading
    render: (element) => (isValidating ? element : <Loading />),
  });
}
Enter fullscreen mode Exit fullscreen mode

you can use jsx style

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>
    ),
  });
Enter fullscreen mode Exit fullscreen mode

Dynamic Menus

react-router-auth-plus automatically passes children to Layout. You do not need to pass children to Layout in the route configuration. If you are using typescript, set the routers type to optional. UseAuthMenus filters out routes that do not have permission.

import { useAuthMenus, AuthRouterObject } from "react-router-auth-plus";

interface LayoutProps {
  routers?: AuthRouterObject;
}

const Layout:FC<LayoutProps> = ({ routers }) => {
   const menus = useAuthMenus(routers);

   ...
}
Enter fullscreen mode Exit fullscreen mode

Tip

if user auth is ["auth1"], home router auth configure ["auth1", "auth2"], will be judged as having permission.

If react-router-auth-plus helps you, can you give me a star? Thanks.

Top comments (0)