Last active
September 28, 2021 10:23
-
-
Save ulexxander/f50633713b872a77eaee8513aadaffb6 to your computer and use it in GitHub Desktop.
Component that embeds ReCAPTCHA from react-google-recaptcha and saves your time in develpment because it can be replaced with placeholder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { forwardRef, useEffect } from "react"; | |
import ReCAPTCHA, { ReCAPTCHAProps } from "react-google-recaptcha"; | |
import { setting } from "../config"; | |
type CaptchaProps = Omit<ReCAPTCHAProps, "sitekey">; | |
const CaptchaPlaceholder: React.FC<{ onClick?: () => void }> = ({ | |
onClick, | |
}) => { | |
return ( | |
<div | |
className="bg-pink-100 px-4 py-2 w-72 shadow rounded" | |
onClick={onClick} | |
> | |
<p> | |
Captcha is disabled, see settings <code>CAPTCHA_ENABLED</code> | |
</p> | |
</div> | |
); | |
}; | |
function makePlaceholderMethods(): ReCAPTCHA { | |
return { | |
getValue: () => "CAPTCHA_TOKEN_PLACEHOLDER", | |
reset() {}, | |
execute() { | |
throw new Error("Not implemented in placeholder"); | |
}, | |
executeAsync() { | |
throw new Error("Not implemented in placeholder"); | |
}, | |
getWidgetId() { | |
throw new Error("Not implemented in placeholder"); | |
}, | |
} as any; | |
} | |
export const Captcha = forwardRef<ReCAPTCHA, CaptchaProps>( | |
({ ...props }, ref) => { | |
const enabled = setting("CAPTCHA_ENABLED"); | |
useEffect(() => { | |
if (!enabled) { | |
props.onChange?.("CAPTCHA_TOKEN_PLACEHOLDER"); | |
if (ref && typeof ref !== "function") { | |
ref.current = makePlaceholderMethods(); | |
} | |
} | |
}, []); | |
if (enabled) { | |
return ( | |
<ReCAPTCHA sitekey={setting("CAPTCHA_KEY")} {...props} ref={ref} /> | |
); | |
} | |
return ( | |
<CaptchaPlaceholder | |
onClick={() => props.onChange?.("CAPTCHA_TOKEN_PLACEHOLDER")} | |
/> | |
); | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment