Reputation: 3
I am working on a complete web app with some components which used multiple decorators (HOC).
I was wondering if there is a way to use multiple decorators with one call.
Something like this:
export default compose(
[
withFunctionality,
withProvider
]
)(MyComponent)
The corresponding code should be:
export default withProvider(
withFunctionality(
MyComponent
)
)
The following code is what i tried:
function compose(hocs) {
return (Component) => hocs.reduce(
(component, hoc) => hoc(component),
Component
)
}
However, when doing like so some of my components doesn't work any more.
What might be wrong here?
Upvotes: 0
Views: 608
Reputation: 7460
You can always use flowRight
function from lodash as compose function.
Here is a practical example in my GraphQL project in order to inject my queries/mutations to my component:
import { graphql } from "react-apollo";
import { flowRight as compose } from "lodash";
... some react code
// export like this
export default compose(
graphql(myQuery),
graphql(myMutation)
)(MyComponent);
This example has been used in GraphSQL context but I think you get the idea of composing some other stuff with your components.
Also here is how flowRight
function works in lodash documentation.
Upvotes: 2