Last active
August 20, 2018 06:38
-
-
Save tricoder42/a8258350c7c1cb69cf41f0f8d3f18169 to your computer and use it in GitHub Desktop.
Headless components RFC https://github.com/sw-yx/rfcs/blob/master/text/0000-React.HeadlessComponent.md
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
const flip = () => ({ | |
flipResults: Math.random() | |
}) | |
// creation of headlesscomponent | |
class CoinFlip extends React.Component { | |
state = flip() | |
handleClick = () => this.setState(flip) | |
api() { | |
return { | |
handleClick: this.handleClick, | |
flipResults: this.state.flipResults, | |
isHeads: this.state.flipResults < 0.5 | |
} | |
} | |
// it seems that HeadlessComponent implements this under the hood. | |
render() { | |
// common pattern for rendering lambda components, but also classic components | |
return React.isValidElement(this.props.children) | |
? React.cloneElement(this.props.children, this.api()) | |
: React.createElement(this.props.children, this.api()) | |
} | |
} | |
<CoinFlip> | |
{({ isHeads, handleClick, flipResults }) => ( | |
<> | |
Flip Results: {flipResults} | |
<button onClick={handleClick}>Reflip</button> | |
{isHeads ? <img src=”/heads.svg” alt=”Heads” /> : <img src=”/tails.svg” alt=”Tails” />} | |
</> | |
)} | |
</CoinFlip> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment