Search code examples
reactjstypescriptinvisible-recaptchareact-google-recaptcha

react-google-recaptcha "ref" type error in React typescript


I'm trying to implement invisible reCaptcha from react-google-recaptcha in type script project

I added the package's type by

yarn add @types/react-google-recaptcha

but when I want to implement the component, I get a type script error in here

  <ReCAPTCHA
        ref={recaptchaRef} // IN HERE
        size="invisible"
        sitekey="Your client site key"
      />

and this is the error's content

 Type 'MutableRefObject<undefined>' is not assignable to type 'LegacyRef<ReCAPTCHA> | undefined'.''
 Type 'MutableRefObject<undefined>' is not assignable to type 'RefObject<ReCAPTCHA>'.
 Types of property 'current' are incompatible.

Solution

  • Just give it an initial value of null. It takes undefined as initial value in your current implementation.

    const recaptchaRef = useRef(null)
    // or
    const recaptchaRef = useRef<ReCAPTCHA>(null);
    
    // ....
    
    <ReCAPTCHA
      ref={recaptchaRef}
      size="invisible"
      sitekey="Your client site key"
    />
    

    Explanation:

    By looking at types, ref attribute expects a type as below:

    (JSX attribute) React.ClassAttributes<ReCAPTCHA>.ref?: string | ((instance: ReCAPTCHA | null) => void) | React.RefObject<ReCAPTCHA> | null | undefined
    

    i.e.

    string | ((instance: ReCAPTCHA | null) => void) | React.RefObject<ReCAPTCHA> | null | undefined
    

    where RefObject is:

    interface RefObject<T> {
      readonly current: T | null;
    }
    

    So, the value of current should be of some type or null.