Skip to content

Instantly share code, notes, and snippets.

@envex
Created June 20, 2019 14:45
Show Gist options
  • Select an option

  • Save envex/ec042ad0c3a3877bcdc320219b2913fe to your computer and use it in GitHub Desktop.

Select an option

Save envex/ec042ad0c3a3877bcdc320219b2913fe to your computer and use it in GitHub Desktop.

Revisions

  1. envex created this gist Jun 20, 2019.
    50 changes: 50 additions & 0 deletions useResizeObserver.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    import { useMemo, useEffect, MutableRefObject } from 'react';

    export default function useResizeObserver(
    targetNode: MutableRefObject<any>,
    callback: (rect: DOMRect) => void,
    ) {
    const observer = useMemo(
    () =>
    // Note: ResizeObserver comes back as unfound even
    // this it's available, so for now I'm just going to
    // ignore the error
    // @ts-ignore
    new ResizeObserver((entries) => {
    for (const entry of entries) {
    callback(entry.contentRect);
    }
    }),
    [callback]
    );

    useEffect(
    () => {
    if (targetNode.current) {
    observer.observe(targetNode.current);

    return () => {
    observer.disconnect();
    };
    }
    return;
    },
    [targetNode.current]
    );
    }

    // We need to push the list down based on the current size of
    // the banner, which can change because the window is resizable
    const resizeCallback = React.useCallback((rect) => {
    if (listRef.current) {
    listRef.current.style.transform = `translateY(${rect.height + OFFSET}px)`;
    }
    }, [listRef]);


    React.useEffect(() => {
    return () => {
    // Reset the FileList bump when the banner is unmounted
    listRef.current.style.transform = `translateY(0px)`;
    };
    }, []);