Home > Software engineering >  How to implement roles and permission base on component in Reactjs?
How to implement roles and permission base on component in Reactjs?

Time:05-28

Here I want to know how to implement roles and permissions for users with multi roles.

Rules like this:

Note : R = Read, W = Write, D = Delete

Role Feature 1 Feature 2 Feature 3
Super Admin RWD RWD RWD
Marketing - R RW
Customer Service - RW R

Please give me example with React Hook for implement this role and permission. Thank you!

CodePudding user response:

Below describes an approach you may take, feel free to change the API design as you see fit.

First, you need a function that maps role to permissions:

function mapRoleToPermissions(role) {
  switch (role) {
    // ...
    case "MARKETING": {
      return {
        feature2: "R",
        feature3: "RW",
      };
    }
    default:
      return {};
  }
}

Then, you can create a React hook with that function:

function usePermissions(role, feature) {
  const permissions = useMemo(() => {
    const permissions = mapRoleToPermissions(role)[feature];
    return {
      canRead: !!permissions?.includes("R"),
      canWrite: !!permissions?.includes("W"),
    };
  }, [role, feature]);

  return permissions;
}

Finally, you may use the React hook in a React component:

function Feature2Form({ role }) {
  const { canWrite } = usePermissions(role, "feature2");
  return (
    <form>
      <fieldset disabled={!canWrite}>
        <input type="text" />
        <button type="submit" />
      </fieldset>
    </form>
  );
}

CodePudding user response:

really you dont need to do anything crazy for storing roles...

const roles = [
  { role: 'superAdmin', display: 'Super Admin', feature1: 'RWD', feature2: 'RWD', feature3: 'RWD' },
  { role: 'marketing', display: 'Marketing', feature1: null, feature2: 'R', feature3: 'RW' },
  { role: 'customerService', display: 'Customer Service', feature1: null, feature2: 'RW', feature3: 'R' }
]
  • Related