@react-rbac/rbac
v0.0.0
Published
React Role Based Access Control module
Maintainers
Readme
React RBAC
What it is?
This a Role Based Access Control library for React.js
Key features:
- Easy to use
- Granular control of each React component
- Roles and actions defined with TypeScript allowing types check
- Implement using hooks or components
- Configure via React Context
Installation
npm i @react-rbac/rbacBasic usage
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { RBACProvider, type Roles } from "@react-rbac/rbac";
// Define only expected roles and actions for you entire app
declare module '@react-rbac/rbac' {
// Define your app roles here
interface RoleOverrides {
editor: string;
viewer: string;
consumer: string;
}
// Define your allowed actions for each role
interface ActionOverrides {
view: string;
}
}
// Define your roles and actions
const roles: Roles = {
admin: {
// Alloed actions for role Admin
action: ['create', 'edit', 'delete', 'view'],
},
editor: {
action: ['create', 'edit', 'view'],
},
viewer: {
action: ['view']
},
consumer: {
action: ['view', 'update']
}
}
createRoot(document.getElementById('root')!).render(
<StrictMode>
{/* Selected user role for your app is "admin" */}
<RBACProvider roles={roles} userRole="admin">
<MyReactApp />
</RBACProvider>
</StrictMode>,
)
Allow component
This component will render the child content only if the user has the role=Admin and allowed action=Create.
<Allow role="admin" action="create">
<button>Admin Create</button>
</Allow>Allow hook
Works in the same ways as Allow component but defined in React hook component.
It will return true only if the user has role=Admin and action=Create.
const [ allow ] = useAllow("admin", "create");Exclude component
This component will exclude rendering content to the defined role with action and allow all the on others.
[!NOTE] This component is useful when you have defined many roles and let's say a button should be display for all the roles except one, so you only need to define that excluded role from rendering content
<Exclude role="admin" action="create">
<button>Admin Create</button>
</Exclude>Exclude hook
Works in the same ways as Exclude component but defined in React hook component.
It will return true only if the user has no role=Admin and action=Create.
const [ exclude ] = useExclude("admin", "create");