HOC ( Higher-order components ) in ReactJS explained

What is a HOC?

In simple words

A HOC is a pure function which takes a component, transforms the component and then returns the newly transformed component.

For e.g

We have an Input component. We want to use it in such a way that the input box will only show if the editMode is true else show a value which we will pass to the component. We can modify the Input component but that would cause problems as the Input is used in multiple places in the application.

A HOC can come and rescue us here. Let’s take a look at our Input component.

The Input component is very simple. It just takes props and passes them to the <input> tag.

Now let’s write a HOC which will actually make the Input tag editable.

Let’s wrap our head around the editableComponent HOC.

For the starters it takes an argument WrappedComponent and then returns a statless functional component.

Inside that functional component, we extract editMode and displayValue from props and store all the other props in restProps.

Finally in the return statment we check if editMode is enabled. If enabled then we return the WrappedComponent and pass all the restProps into it. If not enabled we display a <p> and render displayValue inside it.

That’s pretty much it!!! Now we have a HOC component which will make the Input editable. Let’s use it

Now let’s use the new EditableInput in some expamles.

If you test above examples, you will be to use the EditableInput.

ComponentWithEditableTrue has the editMode sets to true, so our Input component will render.

ComponentWithEditableFalse has the editMode sets to false, so our displayValue will render.

At last but not least, we can still use the Input component as we were using it previously. Also please take notice that apart from displayValue and editMode all the other props are gettings passed to the Input component.

So this is what we call HOC components. They take a component, returns the newly transformed component and render it.

So that was it for this article. If you have any questions and suggestions feel free to comment.

Really loved this article?

Then subscribe to my blog. You will receive articles like this one directly in your Inbox frequently.

Here are more articles for you.

Leave a Reply

Your email address will not be published. Required fields are marked *