Skip to content

Instantly share code, notes, and snippets.

@webpapaya
Last active February 21, 2017 17:31
Show Gist options
  • Save webpapaya/8aefa6588dae67c3c40210462466d9e5 to your computer and use it in GitHub Desktop.
Save webpapaya/8aefa6588dae67c3c40210462466d9e5 to your computer and use it in GitHub Desktop.
Prepare react props before pushing them to a child
// Executes the given fn with the props and applies the result to the component
const prepareProps = (fn) => (Component) => (props) => {
return <Component { ...fn(props) } />
};
const _Child = ({ test }) => {
return (
<div>
{ test /* rendered as "MY PROPERTY" */ }
</div>
);
};
// Modify the props from the parent
// This fn can easily be unit tested
const prepareChildsProps = ({ test }) => ({ test: test.toUpperCase() });
// "Marry" the prepare fn with the _Child component
const Child = prepareProps(prepareChildsProps)(_Child);
// Simply render something
const Parent = () => {
return <Child test="my property" />
};
@johann-sonntagbauer
Copy link

johann-sonntagbauer commented Feb 21, 2017

Nice idea, maybe combining prepareProps with reducers would make the use more generic.

const toUpperCase = (value) => String.prototype.toUpperCase.apply(value);

const prepareProps = (spec) => (Component) => (props) => {
  const updatedProps = Object.assign({}, props, ...Object.keys(spec).map((key) => ( {[key]: spec[key](props[key]) })  ));
  return <Component {...updatedProps}/>
}

const Child = prepareProps({test: toUpperCase})(_Child);

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