Hmmm…your example of a HOC is different from Dan Abramov’s example in the article you linked to.
Tony Garcia
21

Yes, I am doing it slightly differently than Dan, but I linked that article because it explains HOC’s very well from a conceptual and implementation standpoint.

So, in Abramov’s example, he is creating a function that takes a component as an argument and, as you put, returns an “enhanced component” — which is really a wrapper that adds functionality to the argument via composition. In the Tabs example, I am doing something different by having the Tabs component search for the corresponding active child and rendering just that in the content area. However, I could easily compose those components with functionality by cloning them and I’ll explain shortly how to do that in the format I use.

First of all, I wouldn’t focus much on the Tab component. While, Tabs passes functionality onto Tab for switching the active tab when clicked, that is really just part of Tabs. I merely abstracted Tab out cause it looked nice to me. The real magic is where the Tabs HOC searches for the active child component and renders that based on the tab selected. This bit:

As you can see, this function searches for the current child by the contentKey (or the first one if none are selected) and returns it. I like the format I used because it allows many components as I’d like by just adding more children rather than passing a bunch of arguments into a function. Also, if I wanted to pass functionality to the children, I can simply clone them with a function in props. For example, imagine I wanted the child to have access to setting the currentChildKey on the Tabs component, I can pass that to the active child like this:

This is a relatively contrived example, but as you can see, the updated findCurrentChild method now returns a cloned version of the active child with functionality to change theTabs currentChildKey by composing the clone with the function updateCurrentContentKey in its props. The arrow function provides lexical scoping, so this is the Tabs component. If the child, for example Counter, needs to change the active tab, it has the ability to do so by calling this.props.updateCurrentContentKey with a new contentKey.

I hope this example, while not a very useful case, shows the true power of composition, and how you can use it for your own use cases to help add functionality to many children with without using inheritance (mixins). Plus, this implementation looks nice to me:

<Tabs>
<Counter contentKey="Counter" />
<UserForm contentKey="User Form" />
</Tabs>
Like what you read? Give Nick Cantelmi a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.