Last active
October 3, 2017 03:25
-
-
Save dangh/c1d91ce807f7c33322d1346f99428a1e to your computer and use it in GitHub Desktop.
Recompose as HoC and render prop
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 { 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 |
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 { 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 |
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
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