skip to Main Content

I am forwarding a ref and then I want to do something based on its style properties

const Heading = forwardRef( ({children, ref}) => {
  return <h1 ref={ref}>{children}</h1>;
});
   
const H = ({ children}) => {
  const headingRef = useRef();

useEffect(() => {
    const el = headingRef.current;
    console.log(el);
    const style = window.getComputedStyle(el);
});

return <Heading ref={headingRef}>{children}</Heading>
};

but whenever I getComputedStyle el is undefined.

I don’t see how. Obviously it works if I return the h1 with the ref on it directly, but I need to forward the ref to an underlying component and be able to get its current computed style.

2

Answers


  1. I updated your code. It will works fine.

    const Heading = forwardRef(({children, ref}) => {
      return <h1 ref={ref}>{children}</h1>;
    });
       
    const H = ({ children}) => {
        const headingRef = useRef(null);
    
        useEffect(() => {
            const el = headingRef.current;
            if(el) {
                console.log(el);
                const style = window.getComputedStyle(el);
            }
        }, []);
    
        return (
            <Heading ref={headingRef}>{children}</Heading>
        )
    };
    
    Login or Signup to reply.
  2. The ref is not passed as prop. A component accepts single parameter, the props. Used with forwarRef it accepts an additional second parameter, the ref. So, when used with forwardRef, you have to read the ref from the second parameter, not from props.

    Change from this (single parameter):

    forwardRef(({children, ref}) => ...
    

    To this (2 parameters):

    forwardRef(({children}, ref) => ...
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search