react-hcaptcha

repository·master·Indexed 20 days ago

https://github.com/hcaptcha/react-hcaptcha

A React and Preact component library for integrating hCaptcha as a privacy-preserving alternative to reCAPTCHA. It provides the <HCaptcha /> component, an HCaptchaProvider for state management, and a useHCaptcha hook for programmatic access to the hCaptcha client API, including methods to execute and reset challenges.

Tokens
7.8K
Snippets
23
Records
36
Agent score
67%

What's inside @hcaptcha/react-hcaptcha

  1. Overview of React hCaptcha Component Library

    master

    The react-hcaptcha library provides a React component for integrating hCaptcha into your applications. hCaptcha is a privacy-focused alternative to reCAPTCHA.

    Prerequisite: You must sign up at hCaptcha to obtain a sitekey. This library cannot be used without a valid sitekey.

  2. Use the HCaptcha component

    master

    The HCaptcha component is the primary entry point for integrating hCaptcha into a React application. It handles script loading, widget rendering, and provides a bridge to the underlying hCaptcha API. You can pass various configuration props to customize the widget's appearance, behavior, and callbacks.

    import { HCaptcha } from '@hcaptcha/react-hcaptcha';
    
    function MyForm() {
      const handleVerify = (token, ekey) => {
        console.log('Verification token:', token);
        console.log('Response key:', ekey);
      };
    
      return (
        <HCaptcha
          sitekey="YOUR_SITE_KEY"
          onVerify={handleVerify}
          onExpire={() => console.log('Captcha expired')}
          onError={(err) => console.error('Captcha error:', err)}
        />
      );
    }
  3. Troubleshoot: reCAPTCHA conflicts

    master
    If you are running both hCaptcha and reCAPTCHA on the same page, hCaptcha's compatibility mode will interfere with reCAPTCHA because they share property names. To fix this, set the reCaptchaCompat prop to false on your <HCaptcha /> component.
  4. Troubleshoot: Sentry version conflicts

    master

    If the sentry prop is enabled, the hcaptcha-loader package requires Sentry SDK version 8.x or later. If your site uses an older @sentry/browser version, you may see the error g.setPropagationContext is not a function.

    Solutions:

    1. Update your Sentry client to version 8.x or higher.
    2. Set the sentry prop to false on the <HCaptcha /> component to avoid using the bundled Sentry logic.
  5. Implement hCaptcha using the standard component pattern

    master

    The simplest way to use hCaptcha is to include the <HCaptcha /> component within a parent element (like a <form />). You must provide a sitekey. The component automatically handles loading the hCaptcha API library.

    import HCaptcha from '@hcaptcha/react-hcaptcha';
    
    <FormComponent>
        <HCaptcha
          sitekey="your-sitekey"
          onVerify={(token, ekey) => handleVerificationSuccess(token, ekey)}
        />
    </FormComponent>
  6. Implement hCaptcha programmatically using refs

    master

    To call the hCaptcha client API directly (e.g., to trigger a challenge manually), use the useRef hook. It is critical to wait for the onLoad callback to ensure the hCaptcha API is fully loaded and the client is set up before calling methods like .execute().

    import { useEffect, useRef, useState } from "react";
    import HCaptcha from "@hcaptcha/react-hcaptcha";
    
    export default function Form() {
      const [token, setToken] = useState(null);
      const captchaRef = useRef(null);
    
      const onLoad = () => {
        // Reaches out to the hCaptcha JS API and runs the execute function
        captchaRef.current.execute();
      };
    
      useEffect(() => {
        if (token) console.log(`hCaptcha Token: ${token}`);
      }, [token]);
    
      return (
        <form>
          <HCaptcha
            sitekey="your-sitekey"
            onLoad={onLoad}
            onVerify={setToken}
            ref={captchaRef}
          />
        </form>
      );
    }
  7. Use the Provider/Hook pattern for hCaptcha

    master

    For a cleaner architecture, you can wrap your application (or a section of it) in an HCaptchaProvider. This allows any child component to access hCaptcha state and methods via the useHCaptcha hook.

    import { HCaptchaProvider, useHCaptcha } from '@hcaptcha/react-hcaptcha';
    
    function App() {
      return (
        <HCaptchaProvider sitekey="your-sitekey">
          <Form />
        </HCaptchaProvider>
      );
    }
    
    function Form() {
      const { ready, token, executeInstance } = useHCaptcha();
    
      const onSubmit = async () => {
        const response = await executeInstance();
        console.log("Token:", response);
      };
    
      return <button onClick={onSubmit} disabled={!ready}>Submit</button>;
    }
  8. Configure HCaptcha component props

    master

    The HCaptcha component accepts several props to control its behavior and integration with the hCaptcha SDK.

    Core Props

    • sitekey: (Required) Your hCaptcha site key.
    • onVerify: Callback function called when a user successfully completes a challenge. Receives (token, ekey) where token is the response token and ekey is the current challenge session ID.
    • onReady: Callback function called when the captcha widget has been successfully rendered.
    • onLoad: Callback function called when the hCaptcha script has finished loading.
    • onExpire: Callback function called when the captcha response expires.
    • onError: Callback function called when an error occurs.
    • onOpen: Callback function called when the captcha challenge opens.
    • onClose: Callback function called when the captcha challenge closes.
    • onChalExpired: Callback function called when a challenge expires.

    Appearance & Behavior Props

    • size: The size of the widget (e.g., 'normal', 'compact').
    • theme: The visual theme (e.g., 'light', 'dark').
    • languageOverride: Sets the language for the widget.
    • tabindex: Sets the tab index for accessibility.

    Advanced Configuration (Passed to Loader)

    These props are passed directly to the hCaptchaLoader:

    • endpoint: The hCaptcha endpoint.
    • apihost: The API host.
    • assethost: The asset host.
    • host: The host.
    • imghost: The image host.
    • reCaptchaCompat: Boolean to enable/disable reCaptcha compatibility (defaults to true).
    • scriptLocation: Location to find the script element.
    • scriptSource: Source for the script.
    • userJourneys: Boolean to enable user journeys (maps to uj in loader).