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:

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());
      },
    }));

    ...
  }
);

Leave a Reply