Skip to content

Instantly share code, notes, and snippets.

@thinkclay
Created June 21, 2020 16:25
Show Gist options
  • Save thinkclay/d2dc6e8efe6c9fe3ec9828342ace526c to your computer and use it in GitHub Desktop.
Save thinkclay/d2dc6e8efe6c9fe3ec9828342ace526c to your computer and use it in GitHub Desktop.
Restriction HOC
/** @jsx createElement **/
import { createElement, FC, Fragment } from 'react'
import { connect } from 'react-redux'
import { RootState } from '@/models/app'
import { Auth, Roles, roleOptions } from '@/models/auth'
interface Props {
children: React.ReactNode
role?: Roles
roles?: Roles[]
}
interface Connected {
auth: Auth
}
const Restricted: FC<Props & Connected> = ({ children, role, roles, auth }) => {
if (!auth.isLoggedIn) return null
if (role && (!roleOptions[auth.role] || auth.role !== role)) return null
if (roles && !roles.includes(auth.role)) return null
return <Fragment>{children}</Fragment>
}
const mapState = (state: RootState): Connected => ({
auth: state.auth
})
export default connect(mapState)(Restricted)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment