Skip to content

Instantly share code, notes, and snippets.

@loganpowell
Created January 17, 2018 16:30
Show Gist options
  • Save loganpowell/1604f5d4488ac9e78a0e3fda0a6df522 to your computer and use it in GitHub Desktop.
Save loganpowell/1604f5d4488ac9e78a0e3fda0a6df522 to your computer and use it in GitHub Desktop.
React Decorator Pattern: Wrapping Children in Render prop to add functionality
// from: https://www.zhubert.com/blog/2016/02/05/react-composability-patterns/
const CleverParent = React.createClass({
render() {
const children = React.Children.map(this.props.children, (child) => {
return React.cloneElement(child, {
onClick: () => alert(JSON.stringify(child.props, 0, 2))
})
})
return <div>{children}</div>
}
})
const SimpleChild = React.createClass({
render() {
return (
<div onClick={this.props.onClick}>
{this.props.children}
</div>
)
}
})
const App = React.createClass({
render() {
return (
<CleverParent>
<SimpleChild>1</SimpleChild>
<SimpleChild>2</SimpleChild>
<SimpleChild>3</SimpleChild>
<SimpleChild>4</SimpleChild>
<SimpleChild>5</SimpleChild>
</CleverParent>
)
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment