Last active
August 11, 2021 11:11
-
-
Save jordanell/0bbfd717c5ab7bb35a27415ab9682320 to your computer and use it in GitHub Desktop.
React Paywall
This file contains 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 get from 'lodash/get'; | |
import PropTypes from 'prop-types'; | |
import React from 'react'; | |
import { connect } from 'react-redux'; | |
/** | |
* Higher-order component that passes state and props into a predicate that | |
* checks whether the current user has permission to view the page due to paywall restrictions. | |
* | |
* If the predicate function returns true, the component is rendered. | |
* Otherwise, a error is rendered. | |
* | |
* @param {Function} predicate - The paywall predicate function | |
*/ | |
export default function withPaywall(predicate) { | |
const mapStateToProps = (state, ownProps) => { | |
const currentUser = state.currentUser; | |
let hasPermission = false; | |
hasPermission = !!predicate(currentUser, ownProps, state); | |
return { | |
hasPermission, | |
}; | |
}; | |
return (Component) => { | |
class WithPaywallHOC extends React.Component { | |
static propTypes = { | |
// connect | |
/** | |
* Whether the user has permission to access this page. | |
*/ | |
hasPermission: PropTypes.bool.isRequired, | |
} | |
render() { | |
const { | |
hasPermission, | |
} = this.props; | |
if (!hasPermission) { | |
return ( | |
<div> | |
You must pay to continue! | |
</div> | |
); | |
} | |
return ( | |
<Component {...this.props} /> | |
); | |
} | |
} | |
return connect(mapStateToProps)( | |
WithPaywallHOC | |
); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment