GoogleReCaptcha Context has not yet been implemented
See original GitHub issueThanks for creating this library! I have run into a small issue however, and I’m curious whether my use case is supported.
The executeRecaptcha function returned by useGoogleReCaptcha throws a GoogleReCaptcha Context has not yet been implemented error when I try to use GoogleReCaptchaProvider on specific pages, rather than the entire app (in ReactDOM.render). I only want to use it on my app’s signup and forgot password pages, because I don’t want Google’s reCAPTCHA logo in the lower right corner of every page of the app. (It’s especially in the way on mobile.)
I’m guessing this is a consequence of using React Context, so you can’t use the provider and the hook/consumer in the same component. If so, I think the error message could be improved, such as You can only call useGoogleReCaptcha in a component that is wrapped in GoogleReCaptchaProvider. It would also be helpful if the documentation provided guidance or an example of using the library on specific pages.
import React from 'react';
import { GoogleReCaptchaProvider, useGoogleReCaptcha } from 'react-google-recaptcha-v3';
const { REACT_APP_RECAPTCHA_SITE_KEY } = process.env;
export default function SignupPage(): React.ReactElement {
const { executeRecaptcha } = useGoogleReCaptcha();
const onSubmit = React.useCallback(
(event: React.FormEvent) => {
event.preventDefault();
if (!executeRecaptcha) return;
(async () => {
try {
const token = await executeRecaptcha('signup'); // throws context error
// ...
} catch (e) {
// ...
}
})();
},
[executeRecaptcha]
);
return (
<GoogleReCaptchaProvider reCaptchaKey={REACT_APP_RECAPTCHA_SITE_KEY} scriptProps={{ async: true }}>
<form onSubmit={onSubmit} noValidate>
{/* ... */}
</form>
</GoogleReCaptchaProvider>
);
}
This version seems to work:
export default function SignupPage(): React.ReactElement {
return (
<GoogleReCaptchaProvider reCaptchaKey={REACT_APP_RECAPTCHA_SITE_KEY} scriptProps={{ async: true }}>
<SignupForm />
</GoogleReCaptchaProvider>
);
}
function SignupForm(): React.ReactElement {
const { executeRecaptcha } = useGoogleReCaptcha();
const onSubmit = React.useCallback(
(event: React.FormEvent) => {
event.preventDefault();
if (!executeRecaptcha) return;
(async () => {
try {
const token = await executeRecaptcha('signup');
// ...
} catch (e) {
// ...
}
})();
},
[executeRecaptcha]
);
return (
<form onSubmit={onSubmit} noValidate>
{/* ... */}
</form>
);
}
Issue Analytics
- State:
- Created 2 years ago
- Reactions:7
- Comments:7 (3 by maintainers)
Top Related StackOverflow Question
Hello @t49tran , based on @trevorr example I suppose the snippet in https://github.com/t49tran/react-google-recaptcha-v3#react-hook-usegooglerecaptcha-recommended-approach should be updated right? with empty dependencies this will also throw
Execute recaptcha not yet available. It should be written this way:add these code to your css