Created
January 26, 2018 11:19
-
-
Save srph/64b3a17a0082d6cddf5e2fea1b556baa to your computer and use it in GitHub Desktop.
React: Building permission HOCs
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 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; | |
| } | |
| }) | |
| } |
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 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