Reputation: 6017
I am trying to get my head around on how recompose works. Although I understand the underlying concept of it I have a problem with using withProps
function. If I try using it for decorating each child of a component with additional props it simply fails to work. What I do is:
const decorateChild = withProps({ /* some additional props */ });
// ... later on
{ React.Children.map(this.props.children, decorateChild) }
And it simply doesn't work. I had to do React.cloneElement
instead. Could you please help me with that. Here's a sandbox. Please, notice WrappedComponent.js
line number 9
EDIT (The code I have problem with...)
so this works fine:
const decorateChild = actions => child =>
typeof child === "function"
? child(actions)
: React.cloneElement(child, actions);
however I wanted to have it written using recompose. As I said before, if instead of cloneElement
I try to do withProps(action)(child)
it won't work -> nothing gets rendered. If I try forcing the component to render by withProps(action)(child)()
the app crashes.
In general, I wonder how entire WrappedComponent.js
could be expressed using recompose. What I dislike about current implementation is how I have to manually manage ref because the underlying component that I'm using (here Wrap
) requires it and this is something I cannot change (3rd party library). I would also love to handle it using recompose
I hope this little explanation makes it a bit more clear what I'm after.
Upvotes: 3
Views: 4511
Reputation: 4876
withProps
returns a function whose input is another Component (note that child
here is the output of a component i.e. the opaque JS object that represents it), also decorateChild(action)
should return the opaque data structure which explains why you need to call it as a function again
Probably the following looks worse than what you did with React.cloneElement
but it works:
const decorateChild = actions => child => {
const Component = (props) => ({ ...child, props: { ...child.props, ...props } })
return typeof child === "function"
? child(actions)
: withProps(actions)(Component)();
// this also works
// : withProps(actions)((props) => React.cloneElement(child, props))();
};
https://codesandbox.io/s/mjx0626wx8
Upvotes: 3