I'm trying to work with a team building a React application, and trying to figure out the best way to create a "higher-order" React component (one that wraps another) to perform Authentication in conjunction with the Redux data store.
My approach thus far has been to create a module that consists of a function that returns a new React component depending on whether or not there is an authenticated user.
export default function auth(Component) {
class Authenticated extends React.Component {
// conditional logic
render(){
const isAuth = this.props.isAuthenticated;
return (
<div>
{isAuth ? <Component {...this.props} /> : null}
</div>
)
}
}
...
return connect(mapStateToProps)(Authenticated);
}
This makes it easy for other people on my team to specify whether or not a component requires certain permissions.
render() {
return auth(<MyComponent />);
}
If you are performing role-based checks, this approach makes sense, as you may only have a few roles. In such a case, you could just call auth(<MyComponent />, admin)
.
Passing arguments becomes unwieldy for permissions-based checks. It may however be feasible to specify permissions at the component level as the components are being constructed (as well as manageable in a team environment). Setting static methods/properties seems like a decent solution, but, as far as I can tell, es6 classes export as functions, which don't reveal callable methods.
Is there a way to access the properties/methods of an exported React component such that they can be accessed from a containing component?