0

I am wondering how I can find the DOM node of a React child. This question has been asked before, however in every solution I can find (like this one), the accepted answer makes use of ReactDOM.findDOMNode. I don't consider this to be an ideal solution since use of ReactDOM.findDOMNode is discouraged, and it may be deprecated in the future.

If have looked into creating a new ref with React.createRef() from cloneElement, but this doesn't seem to provide a way of accessing getBoundingClientRect() which I require.

ie.

// in constructor
this.childElement = React.createRef();

...

const newChild = React.cloneElement(
      childElement,
      { ref: this.childElement }
    );

Is there a way of accomplishing this without ReactDOM.findDOMNode?

Nicholas Haley
  • 3,558
  • 3
  • 29
  • 50
  • Is there something wrong with getting the DOM node of child via `
    this.node = node} />` for example?
    – Shawn Andrews Nov 28 '18 at 03:35
  • In my case, yes. I have a wrapper component which needs to be able to assign a ref to any Component or element passed as `props.children`. – Nicholas Haley Nov 28 '18 at 03:39
  • Can you iterate the children and assign a ref to each? – Shawn Andrews Nov 28 '18 at 03:44
  • In my case the wrapper should only ever take in one child, so I do `const childElement = React.Children.only(this.props.children);` As shown above, this element is cloned and I try to assign a ref (but obviously the node doesn't seem to work as intended since I cannot call `getBoundingClientRect`). This should effectively be the same as iterating through and assigning refs. – Nicholas Haley Nov 28 '18 at 04:01

0 Answers0