npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

react-role-guard

v0.0.2

Published

Simple role-based guard for React and React Native

Downloads

6

Readme

React Role Guard

npm version License: MIT

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-guard

or

yarn add react-role-guard

Quick 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

  1. Server-Side Validation: Always validate permissions on the server-side. This component is for UI purposes only.

  2. 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);
};
  1. 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

  1. Clone the repository
  2. Install dependencies: npm install
  3. Make your changes
  4. Build the project: npm run build
  5. Test your changes
  6. 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!