Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Ghanshyam-K-Dobariya/a23b0c0a26a482e43473d8a3a2867150 to your computer and use it in GitHub Desktop.
Save Ghanshyam-K-Dobariya/a23b0c0a26a482e43473d8a3a2867150 to your computer and use it in GitHub Desktop.

Create a higher order function that accepts a react component. Do logs when life cycle methods (componentWillReceiveProps or render) are called

F1.js

export function hocF (Component) {
  const cwp = Component.prototype.componentWillReceiveProps;
  Component.prototype.componentWillReceiveProps = function(...args) {
    console.log('in Component will receive props....')
    cwp.call(this, ...args)
  }

  const ren = Component.prototype.render;
  Component.prototype.render = function() {
    console.log('in render...')
    return ren.call(this) /* render method must return something so you must return from this function */
  }

  return Component;
}

Component1.js

import hocF from './F1'

class Component1 extends React.Component {
    constructor(props) {
        super(props);
       // ... constructor code....
    }

   componentWillReceiveProps(nextProps) {
     // your code...
   }
   render() {
       // your code... returning something... 
   }
}

export default hocF(Component1)

Learned from internal tech talks in my company - Tekion Corp.

Thanks to my mentor (& presenter of this topic) : Nitish Kumar

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment