Skip to content

Instantly share code, notes, and snippets.

@srph
Last active January 26, 2018 21:22
Show Gist options
  • Save srph/6b7a3f97559cb38c6f697c2b77389d9a to your computer and use it in GitHub Desktop.
Save srph/6b7a3f97559cb38c6f697c2b77389d9a to your computer and use it in GitHub Desktop.
React: Compose HOCs on-the-go without variable assignment (https://github.com/srph/react-hoc-compose)

Why

Since we do permissions this way:

<App>
  <Route path="/login" component={Permission.guest(AppLogin)} />

  <Permission.auth(AppMain)>
    <Route path="/" component={AppHome} />
    <Route path="/trash" component={AppHome} />
  </Permission.auth(AppMain)>
</App>

And that <Permission.auth(AppMain)> isn't a valid syntax, we may have to make assign it to a variable.

const AppMainWithPermission = Permission.auth(AppMain)

which can get verbose. What if we could compose it on the go?

<Compose hoc={Permission.auth} component={AppMain}>
</Compose>

Installing

See react-hoc-compose.

import React, {cloneElement} from 'react'
/**
* Make it easier to apply HOC to a component
* without having to assign it to a variable
*/
class Compose extends React.Component {
applied = this.props.hoc(this.props.component)
render() {
const {hoc, component, ...props} = this.props
const Applied = this.applied
return <Applied {...props} />
}
}
export default Compose
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment