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
I updated your code. It will works fine.
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 withforwardRef
, you have to read the ref from the second parameter, not from props.Change from this (single parameter):
To this (2 parameters):