Exporting React component with multiple HOC wrappers? Exporting React component with multiple HOC wrappers? javascript javascript

Exporting React component with multiple HOC wrappers?


You can use compose from redux or recompose. For example:

Redux

import { compose } from 'redux'export default compose(  withResource,  withSocket,  withNotifications)(TextComponent)

Recompose

import { compose } from 'recompose'export default compose(  withResource,  withSocket,  withNotifications)(TextComponent)


It's called functional composition and it has mathematical background (that causes y and x variables naming and reversed execution of functions). It decreases complexity of the way how you call written functions by eliminating variables extra definition and deep level of function wrapage.

Write it by yourself or use from a library like: lodash, rambda, redux, etc.

const compose = (...rest) => x => rest.reduceRight((y, f) => f(y), x)

Usage with first class functions:

const increment = (numb) => numb + 1const multiplyBy = (multiplyNum) => (num) => multiplyNum * numcompose(increment, multiplyBy(3), increment)(4)// 4 > 5 > 15 > 16

Usage with higher order components:

compose(withRouter, withItems, withRefs)(Component) 


Another simple solution can be to do this in three steps, simply putting the HOC components on top of each other like this:

const firstHOC = withNotifications(TextComponent);const secondHOC = withSocket(firstHOC);export default withResource(secondHOC);