Higher Order Components

The last Component composition pattern we will examine in this section is Higher Order Components (HOC). As @dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750#.b74nxbqew">Dan Abramov discusses, Higher Order Components were first proposed by Sebastian Markbåge in a gist. The core idea of HOC is to define a function, which you pass one or more Components to. This function generates and returns a new Component, which is a wrapper around the passed in Component(s).

The need for HOC came about with React’s move to support ES6 classes and the lack of mixin support with the new JavaScript Class syntax. To handle this change, a new pattern needed to be defined to replace mixins. Typically, mixins add/override functionality around the Component Life Cycle and enable sharing reusable code in a elegant way. Without mixin support in ES6, the HOC pattern is required.

A form group example

For our HOC example, we will create a function for wrapping a Component in a custom form group with an optional <label> field. The goal of the HOC is to allow us to create two outputs, with and without a label:

  1. <!-- With a label -->
  2. <div class="form-group">
  3. <label class="form-label" for="firstName">First Name:</label>
  4. <input type="text" name="firstName" />
  5. </div>
  6. <!-- Without a label -->
  7. <div class="form-group">
  8. <input type="text" name="lastName" />
  9. </div>

Because this could become a common task, we can use the HOC pattern to generate our form group wrapper and let it decide if it should inject the label or not.

formGroup.js

  1. import React from 'react';
  2. import { isString } from 'lodash';
  3. function formGroup(Component, config) {
  4. const FormGroup = React.createClass({
  5. __renderLabel() {
  6. // check if the passed value is a string using Lodash#isString
  7. if (isString(this.props.label)) {
  8. return(
  9. <label className="form-label" htmlFor={ this.props.name }>
  10. { this.props.label }
  11. </label>
  12. );
  13. }
  14. },
  15. __renderElement() {
  16. // We need to see if we passed a Component or an Element
  17. // such as Profile vs. <input type="text" />
  18. if (React.isValidElement(Component)) return React.cloneElement(Component, this.props);
  19. return( <Component { ...this.props } />);
  20. },
  21. render() {
  22. return(
  23. <div className="form-group">
  24. { this.__renderLabel() }
  25. { this.__renderElement() }
  26. </div>
  27. );
  28. }
  29. });
  30. return(<FormGroup { ...config } />);
  31. }
  32. export default formGroup;

To use this HOC we can do the following:

index.js

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. import formGroup from './higherOrderComponents/formGroup';
  4. let MyComponent = React.createClass({
  5. render() {
  6. return (
  7. <div>
  8. { formGroup(<input type="text" />, { label: 'First Name:', name: 'firstName' }) }
  9. </div>
  10. );
  11. }
  12. });
  13. ReactDOM.render(<MyComponent />, document.getElementById('mount-point'));

Let’s examine the above code. The first thing we do for the HOC is create a function called formGroup which takes two arguments: Component and config.

  1. function formGroup(Component, config) {
  2. ...
  3. }
  4. export default formGroup;

The Component will be the instance we want to wrap in our form group. In the function, we create a new React Component and then return an Element instance using the config as props.

  1. const FormGroup = React.createClass({
  2. ...
  3. });
  4. return(<FormGroup { ...config } />);

We take advantage of the ES6 spread operator to pass in our config object as the props for the generated JSX Element. In our render() method we create the form group <div> and then render out our optional label and Component content.

  1. render() {
  2. return(
  3. <div className="form-group">
  4. { this.__renderLabel() }
  5. { this.__renderElement() }
  6. </div>
  7. );
  8. }

In our __renderLabel() method[^1] we use the Lodash isString method to check if the label value is a string. If so, we render out our label DOM element, otherwise we return null.

  1. __renderLabel() {
  2. // check if the passed value is a string using Lodash#isString
  3. if (isString(this.props.label)) {
  4. return(
  5. <label className="form-label" htmlFor={ this.props.name }>
  6. { this.props.label }
  7. </label>
  8. );
  9. }
  10. },

Because null does not render out to the Native UI in React, this is how we make the <label> optional based on the passed value.

Finally, we had to add a check to determine what type was passed to our HOC function for the Component. This is an important check because we want to support both React Components and Elements.

In our index.js we are passing in:

  1. formGroup(<input type="text" />, { label: 'First Name:', name: 'firstName' })

Because we are using JSX to generate our <input /> the HOC will receive an Element. But, if we used our Profile component, we may not want to use JSX:

  1. formGroup(Profile, { label: 'First Name:', name: 'firstName' })

To support both options and pass on the props, we use the __renderElement() method to handle the inspection and output generation:

  1. __renderElement() {
  2. // We need to see if we passed a Component or an Element
  3. // such as Profile vs. <input type="text" />
  4. if (React.isValidElement(Component)) return React.cloneElement(Component, this.props);
  5. return( <Component { ...this.props } />);
  6. },

If the Component instance is an element, we clone the element and pass on the new props. Otherwise, we generate a new Element using JSX and the passed in React Component.

This HOC example is just the tip of the iceberg when it comes to self-generating wrapper components. Using this pattern, we can tap into the Component Life Cycle methods, we can make more complex decisions based on the data, we can register to stores or other events, and many other possible combinations.

For more in-depth examples we highly recommend reading Dan Abramov’s @dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750#.9y0gg1ix5">Mixins Are Dead. Long Live Composition and @franlplant’s @franleplant/react-higher-order-components-in-depth-cf9032ee6c3e#.d38rbnsu8">React Higher Order Components in depth


[^1] In these examples we are prefixing our methods with __ to reflect that these are internal component methods. This is completely optional and is just our preferred style syntax.