Last active
August 29, 2015 14:21
-
-
Save elierotenberg/f6386fbec5f88c337be7 to your computer and use it in GitHub Desktop.
TransformProps
This file contains hidden or 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 TransformProps = (Component, transform) => class extends React.Component { | |
| displayName = Component.displayName; | |
| render() { | |
| return <Component {...transform(this.props)}>; | |
| } | |
| }; | |
| const transform = (f) => (t) => { | |
| r = {}; | |
| Object.keys(t).forEach((k) => r[k] = f(t[k], k)); | |
| return r; | |
| }; | |
| TransformProps(class extends React.Component { | |
| render() { | |
| // all props values have been multiplied by 2 | |
| } | |
| }, transform((x) => 2*x)); // simple transform: all props are multiplied by two | |
| TransformProps(class extends React.Component { | |
| render() { | |
| // only two props: sum and mean | |
| } | |
| }, (props) => { // less trivial transform: new props are the sum and the mean of previous props | |
| let sum = 0; | |
| Object.keys(props).forEach((k) => sum += props[k]); | |
| return { sum, mean: sum/Object.keys(props).length }; | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very pure, very composable props transformer.