Skip to content

Instantly share code, notes, and snippets.

@gtindo
Created September 15, 2020 08:54
Show Gist options
  • Save gtindo/e46f0d254e464fb13545d982f2b67956 to your computer and use it in GitHub Desktop.
Save gtindo/e46f0d254e464fb13545d982f2b67956 to your computer and use it in GitHub Desktop.
Can component renders his children if user has permissions listed in permissions prop
import * as React from "react";
import { LoginContext } from "../components/login"
type CanPropsType = {
permissions: string[],
children: React.ReactNode
}
const hasPerms = (userPermissions: string[], componentPermissions: string[]): boolean => {
for(let permission of componentPermissions){
if(!userPermissions.includes(permission)) return false;
}
return true;
}
export const Can: React.FunctionComponent<CanPropsType> = (props) => {
const loginContext = React.useContext(LoginContext);
return (
<>
{loginContext?.state.isAdmin || hasPerms(loginContext?.state.permissions || [], props.permissions) ?
<>{props.children}</> : <> </>
}
</>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment