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

useImperativeHandle – Property 'ref' does not exist on type 'IntrinsicAttributes & ResultsConnectedProps'

I’m getting an error when trying to pass a ref to a forwardedRef component. Here’s the forwardRef component:

interface ResultsConnectedProps {
  sql: string;
}

export const ResultsConnected: FC<ResultsConnectedProps> = forwardRef(({ sql }, ref) => {
  const [lastUpdateAt, setLastUpdateAt] = useState(0);

  useImperativeHandle(ref, () => ({
    runQuery: () => {
      setLastUpdateAt(Date.now());
    },
  }));

 ...
});

And I’m then declaring it in a parent like this:

const resultsRef = useRef(null);

...

<ResultsConnected ref={resultsRef} sql={sql} />

This results in the following error:

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

Type '{ ref: MutableRefObject<null>; sql: string; }' is not assignable to type 'IntrinsicAttributes & ResultsConnectedProps'.
  Property 'ref' does not exist on type 'IntrinsicAttributes & ResultsConnectedProps'.ts(2322)
(property) ref: React.MutableRefObject<null>

>Solution :

export const ResultsConnected: FC<ResultsConnectedProps>

By assigning this the type FC<ResultsConnectedProps> you’ve wiped out any information about the ref. forwardRef includes type information, and is written as a generic, so i recommend you do this:

interface ResultsConnectedProps {
  sql: string;
}

interface ResultsConnectedRef {
  runQuery: () => void;
}

export const ResultsConnected = forwardRef<ResultsConnectedRef, ResultsConnectedProps>(
  ({ sql }, ref) => {
    const [lastUpdateAt, setLastUpdateAt] = useState(0);

    useImperativeHandle(ref, () => ({
      runQuery: () => {
        setLastUpdateAt(Date.now());
      },
    }));

    ...
  }
);
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