Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

187
Views
React & Typescript passing HTML types into custom hook

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;
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>();
about 4 years ago · Juan Pablo Isaza Report

0

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 });
    });

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!