react-google-recaptcha-v3 icon indicating copy to clipboard operation
react-google-recaptcha-v3 copied to clipboard

Proposal: Expose GoogleReCaptcha Context

Open lgants opened this issue 2 years ago • 1 comments

There is currently no way to access the context directly (to my knowledge). Exposing the context could be handy for layering providers. For example, if someone integrates ReCaptcha in all their forms out-of-the-box, but they also have a few buttons that need it, which may be on the same page as the form (at different positions in the hierarchy). If context is exposed, they could do something like this:

import {
  GoogleReCaptchaContext,
  GoogleReCaptchaProvider,
  useGoogleReCaptcha
} from 'react-google-recaptcha-v3';

const MyReCaptchaProvider = ({ children }) => {
  // Attempt to access provider context; will be undefined when provider does not exist
  const context = useContext(GoogleReCaptchaContext);

  // Provider already exists in the hierarchy; don't duplicate
  if (context) {
    return <>{children}</>
  }

  // Provider does not exist; must initialize it
  return (<GoogleReCaptchaProvider>{children}</GoogleReCaptchaProvider>)
}

Thoughts on that? Only change this library would need is exposing the context.

lgants avatar Nov 21 '21 21:11 lgants