Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
TransformProps
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 };
});
@elierotenberg

This comment has been minimized.

Copy link
Owner Author

@elierotenberg elierotenberg commented May 26, 2015

Very pure, very composable props transformer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment