How would I pass the type annotation using the as SVGElement or as HTMLDivElement etc...
into a hook
function AppSVG(){
const ref = useResizeObserver((entry) => {
...
}) as SVGElement;// <- how do I pass SVGElement to the hook
return <svg ref={ref} />
}
function AppDiv(){
const ref = useResizeObserver((entry) => {
...
}) as HTMLDivElement;// <- how do I pass HTMLDivElement to the hook
return <div ref={ref} />
}
The hook
function useResizeObserver(observerCallback: ResizeObserverCallback) {
const ref = React.useRef<any>(null);//<- into the ref
React.useEffect(() => {
if (!!ref && !!ref.current)
new ResizeObserver(observerCallback).observe(ref.current);
}, []);
return ref;
}
With Generics you can pass your type in as a sort of argument. useRef takes a generic itself, so you can create your own generic type and pass it into useRef.
function useResizeObserver<T>(observerCallback: ResizeObserverCallback) {
const ref = React.useRef<T>(null);//<- into the ref
...
}
use:
const ref = useResizeObserver<HTMLDivElement>();
more or less this is what I was going for Bastiat's answer was nearly complete. I had to include <T extends Element>.
hook:
function useResizeObserver<T extends Element>(observerCallback: (element: T, entry: ResizeObserverEntry[]) => void, options?: ResizeObserverOptions) {
const ref = React.useRef<T>(null);
React.useEffect(() => {
if (!!ref && !!ref.current) {
const element = ref.current;
new ResizeObserver((entry) => observerCallback(element, entry)).observe(element, options);
}
}, []);
return ref;
}
component:
const ref = useResizeObserver<HTMLDivElement>((element) => {
const height = element.offsetWidth;
const width = element.offsetHeight;
setState({ width, height });
});