t49tran / react-google-recaptcha-v3

Google Recaptcha V3 integration for React
MIT License
437 stars 91 forks source link

Proposal: Expose GoogleReCaptcha Context #108

Open lgants opened 2 years ago

lgants commented 2 years ago

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.

t49tran commented 2 years ago

Hi @lgants, don't think I fully understand your use case here, does it means you need to access recaptcha function from multiple components ? In that case, you only need a single GoogleReCaptchaProvider on top or near the top of the component hierarchy. I don't see why the GoogleReCaptchaProvider needs to be conditional rendered multiple time in the same React tree. If you have multiple form or buttons that need access to recaptcha functions, wrap them all under a single provider should be enough.