UNPKG

react-recaptcha-hook

Version:
63 lines (58 loc) 1.89 kB
import * as React from 'react'; import useScript from 'react-script-hook'; function useRecaptcha({ sitekey, hideDefaultBadge = false, checkForExisting = true }) { const [recaptcha, setRecaptcha] = React.useState(); React.useEffect(() => { if (isBrowser && hideDefaultBadge) { injectStyle('.grecaptcha-badge { visibility: hidden; }'); } }, [hideDefaultBadge]); useScript({ src: `https://www.google.com/recaptcha/api.js?render=${sitekey}`, onload: () => window.grecaptcha.ready(() => { setRecaptcha(window.grecaptcha); }), checkForExisting }); React.useEffect(() => { if (window.grecaptcha) { window.grecaptcha.ready(() => { setRecaptcha(window.grecaptcha); }); } }, []); return action => { return new Promise((resolve, reject) => { if (recaptcha) { resolve(recaptcha.execute(sitekey, { action })); } else { reject(new Error('Recaptcha script not available')); } }); }; } const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined'; const injectStyle = rule => { const styleEl = document.createElement('style'); document.head.appendChild(styleEl); const styleSheet = styleEl.sheet; if (styleSheet) styleSheet.insertRule(rule, styleSheet.cssRules.length); }; const Badge = props => { return /*#__PURE__*/React.createElement("span", props, "This site is protected by reCAPTCHA and the Google", ' ', /*#__PURE__*/React.createElement("a", { href: "https://policies.google.com/privacy", target: "_blank", rel: "noopener noreferrer" }, "Privacy Policy"), ' ', "and", ' ', /*#__PURE__*/React.createElement("a", { href: "https://policies.google.com/terms", target: "_blank", rel: "noopener noreferrer" }, "Terms of Service"), ' ', "apply."); }; export { Badge, useRecaptcha };