Skip to content

Instantly share code, notes, and snippets.

@srph
Created January 26, 2018 11:19
Show Gist options
  • Select an option

  • Save srph/64b3a17a0082d6cddf5e2fea1b556baa to your computer and use it in GitHub Desktop.

Select an option

Save srph/64b3a17a0082d6cddf5e2fea1b556baa to your computer and use it in GitHub Desktop.
React: Building permission HOCs
import React from 'react'
import history from '@/history'
import make from './make'
export default {
/**
* Only guests can enter this page
*/
guest: make((props) => {
if (props.auth.data == null) {
history.push('/')
return false;
}
}),
/**
* Only authenticated users can enter this page
*/
auth: make((props) => {
if (props.auth.data != null) {
history.push('/login')
return false;
}
})
}
import React, {cloneElement} from 'react'
/**
* Permission high-order component
* @param {Function} condition
*/
function make(condition) {
return (Component) => {
class Permission extends React.Component {
state = {
resolved: false
}
componentDidMount() {
if (condition(this.props) !== false) {
this.setState({ resolved: true })
}
}
render() {
if (this.state.resolved) {
return <div />;
} else {
return <Component {...this.props} />;
}
}
}
return Permission
}
}
export default make
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment