Skip to content

Instantly share code, notes, and snippets.

@dangh
Last active October 3, 2017 03:25
Show Gist options
  • Save dangh/c1d91ce807f7c33322d1346f99428a1e to your computer and use it in GitHub Desktop.
Save dangh/c1d91ce807f7c33322d1346f99428a1e to your computer and use it in GitHub Desktop.
Recompose as HoC and render prop
import { compose, withState, withProps } from 'recompose'
function HoCComponent ({a, b, c, setA, setB}) {
return (
<div>
<span>A: {a}</span>
<button onClick={setA}>Update A</button>
<span>B: {b}</span>
<button onClick={setB}>Update B</button>
<span>C: {c}</span>
</div>
)
}
const ComposedComponent = compose(
withState('a', 'setA'),
withState('b', 'setB'),
withProps(({ a, b }) => ({ c: a + b }))
)(HoCComponent)
export default ComposedComponent
import { Composer, compose, withState, withProps } from './render-recompose'
/**
* Assume that `compose` is a high order function that return an object
* describe what to compose. The Composer component will compute the
* actual result and provide it via render prop.
*/
const composeFunc = compose(
withState('a', 'setA'),
withState('b', 'setB'),
withProps(({ a, b }) => ({ c: a + b }))
)
function RenderPropComponent ({a, b}) {
return (
<Composer compose={composeFunc} a={a} b={b}>
{({a, b, c, setA, setB}) => (
<div>
<span>A: {a}</span>
<button onClick={setA}>Update A</button>
<span>B: {b}</span>
<button onClick={setB}>Update B</button>
<span>C: {c}</span>
</div>
)}
</Composer>
)
}
export default RenderPropComponent
function Composer ({compose, children, ...props}) {
return children(compose(props))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment