react-role-guard
v0.0.2
Published
Simple role-based guard for React and React Native
Downloads
6
Maintainers
Readme
React Role Guard
A simple, lightweight role-based access control component for React and React Native applications. Conditionally render components based on user roles with ease.
Features
- 🔒 Simple Role-Based Access Control - Control component visibility based on user roles
- 🎯 TypeScript Support - Fully typed for better development experience
- 📱 React Native Compatible - Works seamlessly with both React and React Native
- 🪶 Lightweight - Minimal bundle size with zero dependencies (except React)
- 🎨 Flexible Fallback - Customizable fallback content when access is denied
Installation
npm install react-role-guardor
yarn add react-role-guardQuick Start
import React from 'react';
import RoleGuard from 'react-role-guard';
function App() {
const userRole = 'admin'; // This would typically come from your auth system
return (
<div>
<h1>My App</h1>
<RoleGuard
allowedRoles={['admin', 'moderator']}
userRole={userRole}
fallback={<p>Access denied. You don't have permission to view this content.</p>}
>
<AdminPanel />
</RoleGuard>
</div>
);
}API Reference
Props
| Prop | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| allowedRoles | string[] | ✅ | - | Array of roles that are allowed to access the content |
| userRole | string | ✅ | - | The current user's role |
| fallback | React.ReactNode | ❌ | null | Component to render when access is denied |
| children | React.ReactNode | ✅ | - | Content to render when access is granted |
Usage Examples
Basic Usage
import RoleGuard from 'react-role-guard';
<RoleGuard
allowedRoles={['admin']}
userRole={currentUser.role}
>
<AdminDashboard />
</RoleGuard>Multiple Roles
<RoleGuard
allowedRoles={['admin', 'editor', 'moderator']}
userRole={user.role}
>
<ContentEditor />
</RoleGuard>With Custom Fallback
<RoleGuard
allowedRoles={['premium', 'admin']}
userRole={user.role}
fallback={
<div className="access-denied">
<h3>Premium Feature</h3>
<p>Upgrade to premium to access this feature.</p>
<button>Upgrade Now</button>
</div>
}
>
<PremiumFeature />
</RoleGuard>Nested Role Guards
<RoleGuard allowedRoles={['user', 'admin']} userRole={user.role}>
<UserDashboard />
<RoleGuard allowedRoles={['admin']} userRole={user.role}>
<AdminControls />
</RoleGuard>
</RoleGuard>React Native Example
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import RoleGuard from 'react-role-guard';
export default function App() {
const userRole = 'user';
return (
<View style={styles.container}>
<Text style={styles.title}>My React Native App</Text>
<RoleGuard
allowedRoles={['admin', 'moderator']}
userRole={userRole}
fallback={
<Text style={styles.errorText}>
You don't have permission to access this feature.
</Text>
}
>
<Text style={styles.successText}>
Welcome to the admin area!
</Text>
</RoleGuard>
</View>
);
}
const styles = StyleSheet.create({
container: { flex: 1, padding: 20 },
title: { fontSize: 24, fontWeight: 'bold' },
errorText: { color: 'red', marginTop: 10 },
successText: { color: 'green', marginTop: 10 },
});Integration with Popular Auth Libraries
With Auth0
import { useAuth0 } from '@auth0/auth0-react';
import RoleGuard from 'react-role-guard';
function MyComponent() {
const { user } = useAuth0();
const userRole = user?.['https://myapp.com/roles']?.[0] || 'guest';
return (
<RoleGuard allowedRoles={['admin']} userRole={userRole}>
<AdminPanel />
</RoleGuard>
);
}With Firebase Auth
import { useAuthState } from 'react-firebase-hooks/auth';
import RoleGuard from 'react-role-guard';
function MyComponent() {
const [user] = useAuthState(auth);
const userRole = user?.customClaims?.role || 'guest';
return (
<RoleGuard allowedRoles={['admin']} userRole={userRole}>
<AdminPanel />
</RoleGuard>
);
}TypeScript
This package is written in TypeScript and includes type definitions. The component is fully typed:
interface RoleGuardProps {
allowedRoles: string[];
userRole: string;
fallback?: React.ReactNode;
children: React.ReactNode;
}Best Practices
Server-Side Validation: Always validate permissions on the server-side. This component is for UI purposes only.
Role Hierarchy: Consider implementing role hierarchy in your application logic:
const getRoleLevel = (role: string): number => {
const hierarchy = { guest: 0, user: 1, moderator: 2, admin: 3 };
return hierarchy[role] || 0;
};
const hasPermission = (userRole: string, requiredRole: string): boolean => {
return getRoleLevel(userRole) >= getRoleLevel(requiredRole);
};- Loading States: Handle loading states when user role is being fetched:
if (isLoading) return <LoadingSpinner />;
return (
<RoleGuard
allowedRoles={['admin']}
userRole={user?.role || 'guest'}
>
<AdminPanel />
</RoleGuard>
);Contributing
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
Development Setup
- Clone the repository
- Install dependencies:
npm install - Make your changes
- Build the project:
npm run build - Test your changes
- Submit a pull request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Author
satishumagol
Keywords
- react
- react-native
- role
- guard
- authorization
- access
- permissions
- rbac
- role-based-access-control
⭐ If you found this package helpful, please consider giving it a star on GitHub!
