Skip to content

Instantly share code, notes, and snippets.

@tricoder42 tricoder42/headless.js
Last active Aug 20, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.