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?

4
  • Is there something wrong with getting the DOM node of child via <div ref={node => this.node = node} /> for example? Commented Nov 28, 2018 at 3: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. Commented Nov 28, 2018 at 3:39
  • Can you iterate the children and assign a ref to each? Commented Nov 28, 2018 at 3: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. Commented Nov 28, 2018 at 4:01

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.