Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'ResizeObserver' only refers to a type, but is being used as a value here

I am getting the error: 'ResizeObserver' only refers to a type, but is being used as a value here when attempting to use ResizeObserver in React with TypeScript.

I have the following interface defined as TypeScript does not include definitions:

interface ResizeObserver {
    observe(target: Element): void;
    unobserve(target: Element): void;
    disconnect(): void;
}

And I am using it in the following component:

const useWidth = () => {

    const ref = useRef<HTMLObjectElement>(null);

    const [width, setWidth] = useState(0);

    useLayoutEffect(() => {

        var resizeObserver = new ResizeObserver(() => console.log("blah blah blah"))
        resizeObserver.observe(ref.current)

        return () => resizeObserver.disconnect()

    }, [ref.current])

    return [ref, width];
}
like image 979
sutherlandahoy Avatar asked Jan 10 '20 14:01

sutherlandahoy


1 Answers

You should install the @types/resize-observer-browser npm package, to get the type declarations. If you really want to roll your own, you can define a newable interface via a declare var in a *.d.ts file.

declare interface ResizeObserver {
  observe(target: Element): void;
  unobserve(target: Element): void;
  disconnect(): void;
}

declare var ResizeObserver: {
  prototype: ResizeObserver;
  new(callback: ResizeObserverCallback): ResizeObserver;
};

interface ResizeObserverSize {
    inlineSize: number;
    blockSize: number;
}

type ResizeObserverCallback = (entries: ReadonlyArray<ResizeObserverEntry>, observer: ResizeObserver) => void;

interface ResizeObserverEntry {
    readonly target: Element;
    readonly contentRect: DOMRectReadOnly;
    readonly borderBoxSize: ResizeObserverSize;
    readonly contentBoxSize: ResizeObserverSize;
}

It'll be available globally then (as I believe it is in the browser) and you can new it up:

enter image description here

like image 90
Meirion Hughes Avatar answered Sep 18 '22 10:09

Meirion Hughes