React - How are props passed to higher order components

React - How are props passed to higher order components
0.0 0

#1

Hello all,

The standard higher order component pattern is something like this:

const HOC = (WrappedComponent) => {
  return class  extends React.Component {
    /**   do some stuff here, modify props, etc  */

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

  }

}

export default HOC;

Despite using these occasionally in the past I have come to realize I don’t understand a major feature of this pattern.

What I dont understand is how the this context is set properly from within the HOC class.

How is it that this.props when called from the HOC will refer to the props of the CHILD component and not the props of the HOC class?

Does anyone know how this passing of props takes place?

Thanks so much!


#2

I am not sure your syntax is right in your example. I would look at this page of the React documentation. Do realize that you can write React components different ways. This page discusses functional components and ES6 class-based components. Your example looks similar but not quite right to their ES6 class-based example.

Props can just be passed into the component where it is rendered, like this:

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

const element = <Welcome name="Sara" />;

Per the example in the React documentation

https://reactjs.org/docs/components-and-props.html