Skip to content

Instantly share code, notes, and snippets.

@jacobrask
Last active June 12, 2016 18:26
Show Gist options
  • Save jacobrask/80bcde3246235ce3b30e528eaccffd28 to your computer and use it in GitHub Desktop.
Save jacobrask/80bcde3246235ce3b30e528eaccffd28 to your computer and use it in GitHub Desktop.
import React from 'react';
// Composes any number of props transforms and applies them in a HOC.
const transform = (...transforms) =>
WrappedComponent =>
props =>
<WrappedComponent {...transforms.reduce((ps, t) => t(ps), props)} />;
// Example reusable transforms.
const addClass = className => props => ({ ...props, className });
const addStyle = styleFn => props => ({ ...props, style: { ...props.style, ...styleFn(props) }});
// "Higher order component factory"
const linkify = transform(
addClass('Link'),
addStyle(props => ({ color: props.disabled ? 'gray' : 'blue' })),
props => ({ ...props, href: '/foo' })
);
const Link = linkify('a');
@acdlite
Copy link

acdlite commented Jun 12, 2016

See Recompose's mapProps

const linkify = mapProps(compose(
  addClass('Link'),
  addStyle(props => ({ color: props.disabled ? 'gray' : 'blue' })),
  props => ({ ...props, href: '/foo' })
));

const Link = linkify('a');

@acdlite
Copy link

acdlite commented Jun 12, 2016

In other words, your transform function is the same as:

const transform = (...transforms) => mapProps(compose(...transforms))
// or (interestingly)
const transform = compose(mapProps, compose)

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