Skip to content

Instantly share code, notes, and snippets.

@ulexxander
Last active September 28, 2021 10:23
Show Gist options
  • Save ulexxander/f50633713b872a77eaee8513aadaffb6 to your computer and use it in GitHub Desktop.
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
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