Skip to content

Instantly share code, notes, and snippets.

@francois-roget
Created May 25, 2021 06:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save francois-roget/0161ae2468d9dee476b87e92db8e208d to your computer and use it in GitHub Desktop.
Save francois-roget/0161ae2468d9dee476b87e92db8e208d to your computer and use it in GitHub Desktop.
import React, {useContext} from 'react';
import PermissionContext from "./PermissionContext";
import {Permission} from "../Types";
type Props = {
to: Permission;
fallback?: JSX.Element | string;
};
// This component is meant to be used everywhere a restriction based on user permission is needed
const Restricted: React.FunctionComponent<Props> = ({to, fallback, children}) => {
// We "connect" to the provider thanks to the PermissionContext
const {isAllowedTo} = useContext(PermissionContext);
// If the user has that permission, render the children
if(isAllowedTo(to)){
return <>{children}</>;
}
// Otherwise, render the fallback
return <>{fallback}</>;
};
export default Restricted;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment