I am trying to get the width of a child’s component in my parent one in react:
import { FC, PropsWithChildren, useRef } from "react";
const MyParent: FC<PropsWithChildren> = (props) => {
const myref = useRef(null);
return (<MyChild ref={myref}/>)
}
const MyChild: FC<PropsWithChildren> = (props) => {
return (<View />)
}
However that won’t compile. I get the following error:
Type ‘{ ref: MutableRefObject; }’ is not assignable to type
‘IntrinsicAttributes & { children?: ReactNode; }’. Property ‘ref’
does not exist on type ‘IntrinsicAttributes & { children?: ReactNode;
}’.ts(2322)
I thought every object could be used as a ref. How can I use a ref to my child?
>Solution :
That’s because ref is a preserved prop from react and you cannot specify it directly as props. But you can use forwardRef function to do so:
import {type PropsWithChildren, forwardRef} from "react";
const MyChild = forwardRef<View, PropsWithChildren>((props, ref) => {
return <View ref={ref} />
})
MyChild.displayName = "MyChild";
You can read more in official documentation (https://react.dev/reference/react/forwardRef)