How to get actual Dom node with React.useRef ? Element.getBoundingClientRect() not working on useRef variable

Viewed 6322

I'm trying to use Element.getBoundingClientRect() to get the x, y, top, left value of dom element.

const editorRef = useRef() 
... // attatched editor ref on the dom element that I'm interested
... 
editorRef.current.focus() // works well 
const editorNodeRect = editorRef.current.getBoundingClientRect() // got error saying getBoundingClientRect() is not a function 

so I tried this way by select the node by query

const editorNodebyQuery =document.querySelectorAll(".DraftEditor-root")[0];
const editorNodebyQueryRect = editorNodebyQuery.getBoundingClientRect() // work well!! 

but I don't like to access the dom node by query.. I think it's heavy.. I want to use the useRef.

first rootEditorNode is what I got by querySelector and it have getBoundingClientRect() function second editorRef.current is what i got by useRef and it doesnt have getBoundingClientRect() funcion.

enter image description here

I just want to know how to use getBoundingClientRect() function with useRef()

1 Answers

Most probably your editorRef is pointing to a React component than a DOM element. you can get the element like this

var element=ReactDOM.findDOMNode(editorRef.current);
var rect =element.getBoundingClientRect();

but ReactDOM.findDOMNode is deprecated in strict mode(recommended to use)

<React.StrictMode></React.StrictMode>

so better way is to use forwardRef if you have access to the Child Component, another option is use a wrapper div which wraps the Child Component and use useRef like this

<div ref={editorRef} >
<ChildComp/>
</div> 

this will allow you to access getBoundingClientRect() might return wrong size(rect.top 0, rect.height 0 etc) in that case you need to call it with a delay

useEffect(() => {

setTimeout(() => {
   var rect = editorRef.current.getBoundingClientRect();
}, 300);

  }, [ ]);
Related