Skip to content

Instantly share code, notes, and snippets.

@tricoder42
Last active August 20, 2018 06:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tricoder42/a8258350c7c1cb69cf41f0f8d3f18169 to your computer and use it in GitHub Desktop.
Save tricoder42/a8258350c7c1cb69cf41f0f8d3f18169 to your computer and use it in GitHub Desktop.
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