1

I'm trying to understand this basic example of HOC :

function ppHOC(WrappedComponent) {

 return class PP extends React.Component {

    constructor(props) {
      super(props)
      this.state = {
        name: ''
      }

    this.onNameChange = this.onNameChange.bind(this)
 }

 onNameChange(event) {
  this.setState({
    name: event.target.value
  })
 }

 render() {
  const newProps = {
    name: {
      value: this.state.name,
      onChange: this.onNameChange
    }
  }
  return <WrappedComponent {...this.props} {...newProps}/>
 }
}

What bugs me is the use of this.props in the return statement :

return <WrappedComponent {...this.props} {...newProps}/>

From what I understand "this" refers to the instance of PP ? So we are instanciating WrappedComponent with the props of PP which are the props of React.Component, am I right ? I do undersatand that we also add newProps to these props but I just don't get what we are doing with this.props here.

Also the constructor of PP is getting some props as parameters. How is PP instanciated exactly ? ppHOC(MyComponent) returns the class PP not really an instance of it right ? In order to instanciate PP you would have to do something like "ppHOC(MyComponent)(someProps)" ?

1 Answers1

0

From what I understand "this" refers to the instance of PP ?

Yes it's correct

So we are instanciating WrappedComponent with the props of PP which are the props of React.Component, am I right ?

Almost there, think of it this way, this is your react structure before HOC: Parent component passes `props` to Child component

Now you wrap your Child with a HOC (ppHOC(Child)) Your structure become: Parent component passes `props` to the component returned from `ppHOC(Child)`, which is class PP

Also the constructor of PP is getting some props as parameters. How is PP instanciated exactly ? ppHOC(MyComponent) returns the class PP not really an instance of it right ? In order to instanciate PP you would have to do something like "ppHOC(MyComponent)(someProps)" ?

It's true that ppHOC(MyComponent) returns the class PP, it will be initiated (rendered) by React when you start using it <MyComponentHOC some="prop" />.

PP is now initiated, { some: "prop" } will be passed in PP's constructor(props) then in turn pass in to your WrappedComponent by (...this.props)

In short, {...this.props} is to pass through whatever props it (the HOC) received to the wrapped component

JayDz
  • 86
  • 1