0

Consider the following higher order component (taken & "simplified" from the React docs):

function withSubscription(WrappedComponent, selectData) {
  return class extends React.Component {
    state = {
      data: selectData(DataSource, props)
    };

   componentDidMount() {
     DataSource.addChangeListener(this.handleChange);
   }

   componentWillUnmount() {
     DataSource.removeChangeListener(this.handleChange);
   }

   handleChange = () => {
     this.setState({ data: selectData(DataSource, this.props) });
   }

   render() {
     return <WrappedComponent data={this.state.data} {...this.props} />;
   }
 };
}

In the render method, all the props initially owned by WrappedComponent are passed on by {...this.props}. However I still have trouble to understand why this happens, since (as far as I know) new function and class declarations have their own this value. This means that the this keyword should(?) belong to the newly returned class, but why is this not happening?

Abraham L
  • 346
  • 2
  • 12
  • 1
    `this` is determined at the time a method is invoked *not* at the time a class is created. This is exactly why you want to have actual methods there. – VLAZ Jan 25 '20 at 21:47
  • 1
    _New function have their own `this` value_: this isn't true anymore since arrow functions, they take the enclosing scope's `this`, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions. – sp00m Jan 25 '20 at 21:50
  • Also, see [How to access the correct `this` inside a callback?](https://stackoverflow.com/q/20279484/1218980) and [React: “this” is undefined inside a component function](https://stackoverflow.com/q/33973648/1218980). – Emile Bergeron Jan 25 '20 at 21:50
  • @Abraham L : Do you understand my response as below ? If yes, please validate my answer. That will motivate us to give you answers. – SanjiMika Jan 26 '20 at 09:11

1 Answers1

1

"withSubscription" is the "HOC function" which will return an "HOC enhanced component"

EnhancedComponent = withSubscription(OriginalComponent);

For using, you will call the EnhancedComponent with his props. "this" here is the context "this" of EnhancedComponent. For example :

<EnhancedComponent p1="test1" p2="test2"/>

So in this case, {...this.props} are p1, p2 of EnhancedComponent which are passed to OriginalComponent.

SanjiMika
  • 2,664
  • 19
  • 19
  • 2
    Why this answer is down voted? – evolon Jan 26 '20 at 01:21
  • @evolon : thank you for your fairness comment ! – SanjiMika Jan 26 '20 at 22:42
  • @SanjiMika Thank you! I assumed following this question was no longer necessary since it was flagged. Regarding your answer, I've finally understood what is going on: I was somehow thinking that the HOC was called based on an already existing component (I know it does not make sense), while it is actually the the HOC which is rendered and has its own props passed to it; hence the use of {...this.props}. – Abraham L Jan 27 '20 at 00:54