react-as-hoc
When you wanted an HOC but some jerk gave you a render-prop component.
Install
yarn add react-as-hoc
API
This function curries a few functions to properly translate all the data in the correct ways. The API is effectively:
type RenderPropFunction = ({children: Function}) => Function;
type PropFn = (props: Object) => Object;
type TransformMethod = (...renderArgs:any) => Object;
type AsHoc = (RenderPropsFunction, ?PropFn) => TransformMethod => React$Component;
Explanation:
const wrappedButNeedsTransform = ; /* * Since render prop functions give you named arguments, there isnt a great way for us to know what the key name for the prop should be. * This `TransformMethod` lets you assign proper keys. It does require you to know what the render prop will return. But That is a requirement * for using any render prop component. * For this example, let's assume our render prop component internally looks like this: * * ```js * const GetCoordinates = ({children}) => children(1, 2); * ``` * * Our GetCoordinates would often be used like `<GetCoordinates>{(x, y) => ...}</GetCoordinates>` * * Here we just trasform the names args into an object to spread into our component */const hoc = ; /* * Now we have our HOC and can wrap our component with it. Which will then get x and y as props. */const Component = ;
Usage
This example is based on react-motion's render Prop API.
// react-motion-hoc.jsimport asHoc from 'react-as-hoc';import Motion spring from 'react-motion'; Motion ownProps defaultStyle: x: 0 style=x: value;
// my-component.jsimport React from 'react';import motionHoc from './react-motion-hoc'; Component<value: Object> { // value from Motion's render prop API console; } MyComponent;
Why
There are some situations where render props just don't make sense. Other times, stylisticly you'd rather have an HOC. The decision should be in your court. Check out all the cool render-prop APIs you can make into HOCs!
License
MIT © Blaine Kasten