Home > Back-end >  Property getBoundingClientRect does not exist on type ParentNode
Property getBoundingClientRect does not exist on type ParentNode

Time:06-29

Was trying to use getBoundingClientRect like:

const menuWrapper = useRef<HTMLElement>(null);
const parentNode = menuWrapper?.current?.parentNode;

const { top, left, height, width } = parentNode?.getBoundingClientRect();

return (
   <div ref={menuWrapper}>
     ...
   </div>
)

But currently can't pass typescript error: Property 'getBoundingClientRect' does not exist on type 'ParentNode'. Anyone that know a way around this?

CodePudding user response:

Try to use parentElement instead of parentNode.

const parentEl = menuWrapper?.current?.parentElement;

Also you can take a look at this to understand the difference.

But anyway, since you are using optional chaining, which meanse everything can be undefined, you can't use top, left, height, and width like this. At least you will need to add something like

if (!parentEl) {
  return;
}

before destructuring.

  • Related