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];
}
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With