Is there a way to create a composition function for decorators in React?

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

Answers (2)

amdev
amdev

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

aleksxor
aleksxor

Reputation: 8360

Here is the classic definition of compose function from the great recompose package:

const compose = (...funcs) =>
  funcs.reduce((a, b) => (...args) => a(b(...args)), arg => arg)

export default compose

If you use redux it has compose function aswell.

Upvotes: -1

Related Questions