Created
January 17, 2018 16:30
-
-
Save loganpowell/1604f5d4488ac9e78a0e3fda0a6df522 to your computer and use it in GitHub Desktop.
React Decorator Pattern: Wrapping Children in Render prop to add functionality
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
// 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