reactjsreact-ref

Why is computed style of this current.ref undefined?


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.


Solution

  • 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) => ...