Home > AI > Frontend > ReactJS >

Higher-Order Components

Concretely, a higher-order component is a function that takes a component and returns a new component.

Example :

import React  from "react";
import ReactDOM from "react-dom";

const HOC = (InnerComponent) => class extends React.Component {
  constructor() {
    super();
    this.state = { count: 0 };
  }

  update () {
    this.setState({ count: this.state.count + 1 });
  }
  render () {
    return (
      // pass self props and state to the children
      <InnerComponent
        {...this.props}
        {...this.state}
        update={this.update.bind(this)}
      />
    );
  }
}


const Button = HOC(
  (props) => (
    <button onClick={props.update}>
      {props.children} - {props.count}
    </button>
  )
);
  

/**
 * props from HOC
 */
class Label extends React.Component {
  render () {
    return (
      <label
        onMouseMove={this.props.update}
      >
        {this.props.type} <br />
        {this.props.children}  <br />
        {this.props.count}
      </label>
    );
  }
}

const LabelHOC = HOC(Label);

class App extends React.Component {
  render() {
    return (
      <div>
        <Button>ButtonInner</Button>
        <hr />
        <LabelHOC type="ra">LabelInner</LabelHOC>
      </div>
    );
  }
}


ReactDOM.render(
  <App />,
  document.getElementById('root')
);

Example 2:

const HelloComponent = ({ name, ...otherProps }) => 
(<div {...otherProps} >
  Hello {name}!
  </div>
);
const withNameOverride = BaseComponent => props =>(
<BaseComponent 
{...props}
name="New Name" 
/>);
const EnhancedHello1 = withNameOverride(HelloComponent);


ReactDOM.render(
  <EnhancedHello1 />,
  document.getElementById('root')
);

Leave a Reply