Created
September 15, 2020 08:54
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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