Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save googya/a8c1f0e5c46adb16d055b2c1e7026803 to your computer and use it in GitHub Desktop.
Save googya/a8c1f0e5c46adb16d055b2c1e7026803 to your computer and use it in GitHub Desktop.
ES6 Higher Order Components

Redux higher order components

Sometimes we need to share props and behaviour between multiple components/containers. For that we can do a higher order component. Example:

Decorator component

Higher Order Component that will decorate other component:

import { Component } from "React";
import { connect } from "react-redux";

function Decorate(ComponentToDecorate) {
  class ComponentDecorated extends Component {
    constructor(props) {
      super(props);
    }

    componentDidMount() {
      // fetch data and stuff
    }

    render() {
      return <ComponentToDecorate {...this.props} />;
    }
  }

  function mapStateToProps(state) {
    return {
      // your shared props
    };
  }

  const mapDispatchToProps = {
    // your shared action call
  };

  return connect(mapStateToProps, mapDispatchToProps)(ComponentDecorated);
}

export default Decorate;

Decorated component:

The actual component that will inherite stuff from the Higher Order Component

import React, { Component } from "react";
import { connect } from "react-redux";
import Decorate from "Decorate.react";

class SomeComponent extends Component {

  constructor(props) {
    super(props);
  }

  componentDidMount() {
  }

  componentWillReceiveProps(nextProps) {
  }

  render() {
    <p> Hello </p>
  );
}

function mapStateToProps(state) {
  return {
    // component specific props
  };
}

const mapDispatchToProps = {
  // component specific action call
};

export default connect(mapStateToProps, mapDispatchToProps)(Decorate(SomeComponent));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment