Introduction

Let’s have a look at Higher Order Components and see how they enable component-based development by dividing components into business and display logic.

What are higher order components?

Higher order components (or HOC or HOCs for short) were, and still are, a central concept in React. They allow you to implement components with reusable logic and are loosely tied to higher order functions from functional programming. These kinds of functions take a function as a parameter and return another function. In terms of React, this principle is applied to components. HOCs derive their name from those higher order functions.

Let us look at an example to illustrate this concept better:

const withFormatting = (WrappedComponent) => {
    return class extends React.Component {
        bold = (string) => {
            return <strong>{string}</strong>;
        };
        italic = (string) => {
            return <em>{string}</em>;
        };
        render() {
            return <WrappedComponent bold={this.bold} italic={this.italic} />;
        }
    };
};

We have defined a function called withFormatting that takes in a React component. The function will return a new React component, which in turn renders the passed component and equips it with the props bold and italic. The component can now access these props:

const FormattedComponent = withFormatting(({ bold, italic }) => (
    <div>
        This text is {bold('bold')} and {italic('italic')}.
    </div>
));

Let’s see and run this example interactively.

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy