3

From this blog article, the rendering of a component can be altered this way:

function iiHOC(WrappedComponent) {
  return class Enhancer extends WrappedComponent {
    render() {
      const elementsTree = super.render()
      let newProps = {};
      if (elementsTree && elementsTree.type === 'input') {
        newProps = {value: 'may the force be with you'}
      }
      const props = Object.assign({}, elementsTree.props, newProps)
      const newElementsTree = React.cloneElement(elementsTree, props, elementsTree.props.children)
      return newElementsTree
    }
  }
}

This seems to work only if the passed components is itself a class component.

How would one go about writing the same code so that it works on functional components ?

Nicolas Marshall
  • 4,186
  • 9
  • 36
  • 54

1 Answers1

-1

I believe you can just pass the props from the wrapper directly to the functional component like so:

const jediEnhancer = (FunctionalComponentToWrap) => {
  return class jediEnhancer extends React.Component {
    constructor(props){
      super(props);

      this.state = {
        forceIsWithUser: false 
      };

      this.awakenTheForce = this.awakenTheForce.bind(this);

    awakenTheForce(){
      this.setState({forceIsWithUser: true});
    }

    render(){
      return <FunctionalComponentToWrap awakenTheForce={this.awakenTheForce} {...this.props} />
    }
  }
}
Matt Waldron
  • 1,738
  • 1
  • 14
  • 11