Nicolas Couvrat
Nicolas Couvrat

Reputation: 371

Use React's high order component with more than one component as argument

I'm fairly new to react-native (and React for this purpose) and I've just started working with high order components. I know that these are supposed to take one component as an argument an return one other component.

My issue here is that I would like my HOC() function to take more than one argument, i.e. something like HOC:: C: React.Component, D: React.Component => H: React.Component(in Haskell-like syntax).

Now, the problem (and reason why I'm posting this) is that it gives me a feeling that my code is a little clunky, because of the way I have to pass props. What I ended up doing is a function taking two arrays, a first array of components and a second one of props, that have to be given in the same order. (so that propList[i] is the props object of the component componentList[i]).

Something like (assuming all imports done):

class MyComponent extends React.Component {
  render() {
    return <Text>{this.props.name}</Text>
  }
}
const HOC = (componentList, propsList) =>
class extends React.Component {
  render() {
    return(
      <View>
        {componentList.map( (Component, index) => {
          return <Component {...propsList[index]} />
        })}
      </View>
    )
  }
}
class App extends React.Component {
  render (){
    //this call is what makes me uncomfortable
    const DoubleComponent = HOC([MyComponent, MyComponent],[{name: 'first'}, {name: 'second'}]); 
    return(
      <DoubleComponent />
    )
  }
}

I've managed to build something like this and it works for what I want it to do, but this question was more about:

I'm also after any 'good practice tip' you guys could give me!

Upvotes: 1

Views: 75

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281656

props are something that HOC can receive from the component props directly

const HOC = (componentList) =>

    class extends React.Component {
      render() {
        return(
          <View>
            {componentList.map( (Component, index) => {
              return <Component {...this.props[index]} />
            })}
          </View>
        )
      }

}
class App extends React.Component {
  render (){
    //this call is what makes me uncomfortable
    const DoubleComponent = HOC([MyComponent, MyComponent]); 
    return(
      <DoubleComponent names={[{name: 'first'}, {name: 'second'}]}/>
    )
  }
}

Upvotes: 2

Related Questions