Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

cannot use ref in function-component

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading