Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get DOM node of wrapped component in a higher order component (HOC)?

How do I get the DOM node of the rendered div from MyComponent inside Enhance in the following example?

Enhance.js

import { Component } from "React";

export var Enhance = ComposedComponent => class extends Component {
  constructor() {
    this.state = { data: null };
  }
  componentDidMount() {
    this.setState({ data: 'Hello' });
  }
  render() {
    return <ComposedComponent {...this.props} data={this.state.data} />;
  }
};

MyComponent.js

import { Enhance } from "./Enhance";

class MyComponent {
  render() {
    if (!this.data) return <div>Waiting...</div>;
    return <div>{this.data}</div>;
  }
}

export default Enhance(MyComponent); // Enhanced component
like image 773
Rotareti Avatar asked Sep 25 '16 22:09

Rotareti


2 Answers

Because your HOC is rendering a child component directly, the data returned by findDOMNode in the HOC should be the child's DOM node.

export var Enhance = ComposedComponent => class extends Component {
    componentDidMount() {
        // Logs the DOM node returned by the wrapped component
        console.log( ReactDOM.findDOMNode( this.refs.child ) );
    }
    render() {
        return <ComposedComponent {...this.props} ref="child" />;
    }
};
like image 126
Andy Ray Avatar answered Oct 14 '22 06:10

Andy Ray


The high order component is the wrapped component itself... enhanced. Getting the dom node of the wrapped component is equivalent to get the dom node of the hoc.

export var Enhance = ComposedComponent => class extends Component {
    componentDidMount() {
        // Logs the DOM node returned by the wrapped component
        console.log( ReactDOM.findDOMNode( this ) );
    }
    render() {
        return <ComposedComponent {...this.props}  />;
    }
};

In this way I can also use forwardRef pattern

export default WrappedComponent => {
  class EnhancedComponent extends React.Component {
    constructor(props) {
      super(props);
    }

    componentDidMount() {
      const domNode = ReactDOM.findDOMNode(this);
      console.log(domNode);
    }

    render() {
      const { forwardedRef, ...otherProps } = this.props;
      return <WrappedComponent ref={forwardedRef} {...otherProps} />;
    }
  }

  const forwardRef = (props, ref) => <EnhancedComponent {...props} forwardedRef={ref} />;
  return React.forwardRef(forwardRef);
};
like image 41
Luca Rasconi Avatar answered Oct 14 '22 07:10

Luca Rasconi