Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useBoundingRects #50

Open
aulneau opened this issue Oct 30, 2018 · 1 comment
Open

useBoundingRects #50

aulneau opened this issue Oct 30, 2018 · 1 comment

Comments

@aulneau
Copy link

aulneau commented Oct 30, 2018

Useful for things like tooltips that need to be aware of their parent and adjust based off of proximity.

import React, { useLayoutEffect, useState } from 'react';

const emptyRect = {
  top: 0,
  right: 0,
  bottom: 0,
  left: 0,
  width: 0,
  height: 0
};

const getRects = el => {
  if (!el)
    return {
      rect: undefined,
      parentRect: undefined
    };

  const parentNode = el.parentNode;

  const rect = el.getBoundingClientRect
    ? el.getBoundingClientRect()
    : emptyRect;

  const parentRect =
    parentNode && parentNode.getBoundingClientRect
      ? parentNode.getBoundingClientRect()
      : emptyRect;

  return { rect, parentRect };
};

export const useBoundingRects = ref => {
  let [{ rect, parentRect }, setRects] = useState(getRects(ref.current));

  const handleResize = () => {
    if (ref && ref.current) {
      setRects(getRects(ref.current));
    }
  };

  useLayoutEffect(() => {
    handleResize();
    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  return [rect, parentRect];
};
@morajabi
Copy link

Thanks @aulneau! This gist is like yours, but a copy of component-size hook, with getBoundingClientRect, which uses resize observer (if not available falls back to 'resize' listener).
https://gist.github.com/morajabi/523d7a642d8c0a2f71fcfa0d8b3d2846

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants