Giter Club home page Giter Club logo

react-hcaptcha's Introduction

React hCaptcha Component Library

hCaptcha Component Library for ReactJS.

hCaptcha is a drop-replacement for reCAPTCHA that protects user privacy.

Sign up at hCaptcha to get your sitekey today. You need a sitekey to use this library.

Also compatible with Preact.

  1. Installation
  2. References
  3. Debugging
  4. Contributing

Installation

You can install this library via npm with:

npm install @hcaptcha/react-hcaptcha --save

Implementation

The two requirements for usage are the sitekey prop and a parent component such as a <form />. The component will automatically include and load the hCaptcha API library and append it to the parent component. This is designed for ease of use with the hCaptcha API!

Standard

import HCaptcha from '@hcaptcha/react-hcaptcha';

<FormComponent>
    <HCaptcha
      sitekey="your-sitekey"
      onVerify={(token,ekey) => handleVerificationSuccess(token, ekey)}
    />
</FormComponent>

Programmatic

In the event you want to call the hCaptcha client API directly, you can do so by using the hook useRef and waiting for onLoad to be called. By waiting for onLoad the hCaptcha API will be ready and the hCaptcha client will have been setup. See the following example:

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 = () => {
    // this reaches out to the hCaptcha JS API and runs the
    // execute function on it. you can use other functions as
    // documented here:
    // https://docs.hcaptcha.com/configuration#jsapi
    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>
  );
}

Typescript Support
If you want to reassign the component name, you could consider making a util that imports the component, then re-exports it as a default.

// utils/captcha.ts
import HCaptcha from '@hcaptcha/react-hcaptcha';
export default HCaptcha;

// MyFormComponent.tsx
import { default as RenamedCaptcha } from '../utils/captcha';
<FormComponent>
  <RenamedCaptcha sitekey="your-sitekey" />
</FormComponent>

Advanced

In most real-world implementations, you'll probably be using a form library such as Formik or React Hook Form.

In these instances, you'll most likely want to use ref to handle the callbacks as well as handle field-level validation of a captcha field. For an example of this, you can view this CodeSandbox. This ref will point to an instance of the hCaptcha API where can you interact directly with it.

Passing in fields like rqdata to execute()

Passing an object into the execute(yourObj) call will send it through to the underlying JS API. This enables support for Enterprise features like rqdata. A simple example is below:

const {sitekey, rqdata} = props;
const captchaRef = React.useRef<HCaptcha>(null);

const onLoad = () => {
  const executePayload = {};
  if (rqdata) {
    executePayload['rqdata'] = rqdata;
  }
  captchaRef.current?.execute(executePayload);
};

return <HCaptcha ref={captchaRef} onLoad={onLoad} sitekey={sitekey} {...props} />;

References

Props

Name Values/Type Required Default Description
sitekey String Yes - This is your sitekey, this allows you to load captcha. If you need a sitekey, please visit hCaptcha, and sign up to get your sitekey.
size String (normal, compact, invisible) No normal This specifies the "size" of the component. hCaptcha allows you to decide how big the component will appear on render, this always defaults to normal.
theme String (light, dark, contrast) or Object No light hCaptcha supports both a light and dark theme. Defaults to light. Takes Object if custom theme is used.
tabindex Integer No 0 Set the tabindex of the widget and popup. When appropriate, this can make navigation of your site more intuitive.
languageOverride String (ISO 639-2 code) No auto hCaptcha auto-detects language via the user's browser. This overrides that to set a default UI language. See language codes.
reCaptchaCompat Boolean No true Disable drop-in replacement for reCAPTCHA with false to prevent hCaptcha from injecting into window.grecaptcha.
id String No random id Manually set the ID of the hCaptcha component. Make sure each hCaptcha component generated on a single page has its own unique ID when using this prop.
apihost String No - See enterprise docs.
assethost String No - See enterprise docs.
endpoint String No - See enterprise docs.
host String No - See enterprise docs.
imghost String No - See enterprise docs.
reportapi String No - See enterprise docs.
sentry String No - See enterprise docs.
secureApi Boolean No - See enterprise docs.
scriptSource String No - See enterprise docs.
cleanup Boolean No true Remove script tag after setup.
custom Boolean No - Custom theme: see enterprise docs.
loadAsync Boolean No true Set if the script should be loaded asynchronously.
scriptLocation Element No document.head Location of where to append the script tag. Make sure to add it to an area that will persist to prevent loading multiple times in the same document view. Note: If null is provided, the document.head will be used.

Events

Event Params Description
onError err When an error occurs. Component will reset immediately after an error.
onVerify token, eKey When challenge is completed. The response token and an eKey (session id) are passed along.
onExpire - When the current token expires.
onLoad - When the hCaptcha API loads.
onOpen - When the user display of a challenge starts.
onClose - When the user dismisses a challenge.
onChalExpired - When the user display of a challenge times out with no answer.

Methods

Method Description
execute() Programmatically trigger a challenge request. Additionally, this method can be run asynchronously and returns a promise with the token and eKey when the challenge is completed.
getRespKey() Get the current challenge reference ID
getResponse() Get the current challenge response token from completed challenge
resetCaptcha() Reset the current challenge
setData() See enterprise docs.

Note
Make sure to reset the hCaptcha state when you submit your form by calling the method .resetCaptcha on your hCaptcha React Component! Passcodes are one-time use, so if your user submits the same passcode twice then it will be rejected by the server the second time.

Please refer to the demo for examples of basic usage and an invisible hCaptcha.

Alternatively, see this sandbox code for a quick form example of invisible hCaptcha on a form submit button.

Please note that "invisible" simply means that no hCaptcha button will be rendered. Whether a challenge shows up will depend on the sitekey difficulty level. Note to hCaptcha Enterprise (BotStop) users: select "Passive" or "99.9% Passive" modes to get this No-CAPTCHA behavior.

Debugging

  1. Invalid hCaptcha Id: <hcaptcha_id>

    This issue generally occurs when the component is re-rendered causing the current useRef to become stale, meaning the ref being used is no longer available in the DOM.

  2. Make sure you don't double-import the api.js script

    Importing the JS SDK twice can cause unpredictable behavior, so don't do a direct import separately if you are using react-hcaptcha.

  3. Make sure you are using reCaptchaCompat=false if you have the reCAPTCHA JS loaded on the same page.

    The hCaptcha "compatibility mode" will interfere with reCAPTCHA, as it adds properties with the same name. If for any reason you are running both hCaptcha and reCAPTCHA in parallel (we recommend only running hCaptcha) then please disable our compatibility mode.

  4. Avoid conflicts with legacy Sentry package usage on react-hcaptcha 1.9.0+

    If you are using Sentry 7.x in your React app, this can conflict with the upstream hcaptcha-loader package's Sentry error tracing. You can avoid this issue by setting the sentry prop to false.


Contributing

Scripts

  • npm run start - will start the demo app with hot reload
  • npm run test - will test the library: unit tests
  • npm run build - will build the production version

Publishing

To publish a new version, follow the next steps:

  1. Bump the version in package.json
  2. Create a Github Release with version from step 1 without a prefix such as v (e.g. 1.0.3)

Running locally for development

Please see: Local Development Notes.

Summary:

sudo echo "127.0.0.1 fakelocal.com" >> /private/etc/hosts
npm start -- --disable-host-check

open http://fakelocal.com:9000 to start the example.

react-hcaptcha's People

Contributors

adekay avatar ajmnz avatar alexandrukis avatar andrepolischuk avatar basicbrogrammer avatar brdlyptrs avatar chris9740 avatar dependabot[bot] avatar dnechay avatar dsergiu avatar e271828- avatar elnygren avatar faris-imi avatar gabrielferreira-imi avatar gaieges avatar hckhanh avatar jad3n avatar jembach avatar josephduffy avatar kdziamura avatar liuboaibc avatar msutkowski avatar nyanbinaryneko avatar timche avatar vladimirjk avatar zane-programs avatar zemlanin avatar zoryana94 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-hcaptcha's Issues

Cannot read property 'postMessage' of null

Hi,

First of all thanks for making this awesome product! I am trying to implement hCaptcha in my side by apparently I can't get it working after I submit the form, it throw me this error Cannot read property 'postMessage' of null and crashed the page.

image (10)

Any idea why this is happening? And this does not happen in my local though.

Would appreciate any help from you all.

Issue with nextjs since v0.3.7

I tried using @hcaptcha/react-hcaptcha with nextjs but the latest version that is working is 0.3.7.

Since 0.3.7 I am always getting the following error:

wait  - compiling / (client and server)...
error - ./node_modules/@hcaptcha/react-hcaptcha/dist/index.js:3:0
Module not found: Can't resolve '@babel/runtime/helpers/interopRequireDefault'

Import trace for requested module:
./pages/index.tsx

https://nextjs.org/docs/messages/module-not-found
wait  - compiling /_error (client and server)...
error - ./node_modules/@hcaptcha/react-hcaptcha/dist/index.js:3:0
Module not found: Can't resolve '@babel/runtime/helpers/interopRequireDefault'

Import trace for requested module:
./pages/index.tsx

https://nextjs.org/docs/messages/module-not-found
error - Error: Cannot find module '@babel/runtime/helpers/interopRequireDefault'
Require stack:
- /hcaptcha-repro/node_modules/@hcaptcha/react-hcaptcha/dist/index.js
- /hcaptcha-repro/.next/server/pages/index.js
- /hcaptcha-repro/node_modules/next/dist/server/require.js
- /hcaptcha-repro/node_modules/next/dist/server/load-components.js
- /hcaptcha-repro/node_modules/next/dist/build/utils.js
- /hcaptcha-repro/node_modules/next/dist/build/output/store.js
- /hcaptcha-repro/node_modules/next/dist/build/output/index.js
- /hcaptcha-repro/node_modules/next/dist/cli/next-dev.js
- /hcaptcha-repro/node_modules/next/dist/bin/next

Reproduction repository: https://github.com/Le0Developer/hcaptcha-repro

Commands to run: npm run dev (dev server) or npm run build (build static files)

invalid-captcha-id

When is the time to show hCaptcha it throws an error in the console
error code : cause: "invalid-captcha-id" message: "Invalid hCaptcha id: 0tb9cvxm5e9m"

Also, I have checked and the site key is correct can someone help?

I have React js for the frontend
Screenshot_1

React native

I would like to put Hcaptcha in React native, can you create the project?

Publish 1.0.0

The package has been published for ~3 years on major version 0, which means minor and patch releases are also treated as breaking changes and won't be automatically updated via npm update or install.

Captcha run in background.

Hi,
I wanted to ask if this library also supports a wrapper which is running in the background which checks if its valid.
Its also known under the name Invisible Captcha.
I can't find any solution.
Best Ragards

Cropped Out Captcha display - Possible to Style HCaptcha? Is it incompatibility in native mobile screen?

I'm using react-hcaptcha with the Ionic Framework, so I would like to see for cross platforms (native and web). I'm checking with Chrome developer tool and checking via responsive screen size. It looks fine of the web (resizing the client too), but when I choose a device (iPhone XR) it gets cut. Note, I refresh the page after I select the device in order to get that device emulator setup. This is all testing on the Chrome browser.
h-00

it's a similar result when I add prop size="compact". It is slightly cropped too.

I'm not sure if this is a bug or incompatibility issue. It has to do with the iframe sizing too. Is there a way to style it and persist? Or is there another option or library that I should be using instead?

Reset Then Remove

A postMessage of null error is thrown when the react-component unmounts. This is due to a timer set for expiring the response token issued when a user passes the captcha.

The componentWillUnmount should first call hcaptcha.reset in order to clear the timer and any other stored variables before removing the iframe from the dom.

Screen Shot 2019-10-25 at 14 09 23

Breaking change in 1.4.0 with typescript and react 17

Recently updating our project from react-hcaptcha 1.3.1 to react-hcaptcha 1.4.3 causes typechecking of some React components to fail (especially nextjs 11.1.4's dynamic components), completely unrelated to the HCaptcha component itself.

Attempting other react-hcaptcha versions (1.3.1 works, and all 1.4.x versions fail) and then checking the dependency changes seems to narrow it down to #139 adding @types/react ^18.0.0 as a production dependency.

Forcing the resolution of the package to 17.0.45 (like our project uses) eliminates all the bogus typechecking errors.

This breaks the typecheck and build step of our project, forcing us to downgrade back to react-hcaptcha 1.3.x

Here is the tsconfig.json we are using

{
	"compilerOptions": {
		"target": "es2015",
		"lib": ["dom", "dom.iterable", "esnext"],
		"allowJs": true,
		"skipLibCheck": true,
		"strict": false,
		"forceConsistentCasingInFileNames": true,
		"noEmit": true,
		"esModuleInterop": true,
		"module": "esnext",
		"moduleResolution": "node",
		"resolveJsonModule": true,
		"isolatedModules": true,
		"jsx": "preserve",
		"importsNotUsedAsValues": "error",
		"paths": {
			"@/*": ["./*"]
		}
	},
	"include": [
		"next-env.d.ts",
		"global.d.ts",
		"**/*.ts",
		"**/*.tsx",
		"**/*.js"
	],
	"exclude": ["node_modules", "build"]
}

And here are the relevant parts of our package.json (with some other omitted packages):

{
	"dependencies": {
		"@hcaptcha/react-hcaptcha": "1.4.3",
		"next": "11.1.4",
		"react": "17.0.2",
		"react-dom": "17.0.2"
	},
	"devDependencies": {
		"@types/react": "^17.0.45",
		"typescript": "^4.7.4"
	},
}

Typechecking is performed by simply running npx tsc at the project root

Enforce reinit on submit to prevent double-submission of passcodes

It’s possible to preserve form state after submission (e.g. for react modals) which may lead to the hCaptcha passcode being cached in the popup->fill form->submit->popup->fill form->submit cycle.

Since passcodes are one-time-use, this will always fail the second time the form is submitted.

Right now we rely on the website to handle this scenario correctly, but safest action would be to explicitly reset state on submit.

Only one captcha is permitted per parent container.

When I try to add hCaptcha to my form it shows Only one captcha is permitted per parent container.
Code:

                <HCaptcha
                  sitekey=process.env.NEXT_PUBLIC_SITE_KEY
                  theme="dark"
                  size="normal"
                  ref={hcaptcha}
                  onVerify={(token) => {
                    setInfo({ ...info, hcaptcha_token: token });
                  }}
                />

Full Error:

next-dev.js?3515:25 Only one captcha is permitted per parent container. 
    at HCaptcha (webpack-internal:///./node_modules/@hcaptcha/react-hcaptcha/dist/index.js:62:37)
    at div
    at div
    at form
    at div
    at section
    at Contact (webpack-internal:///./pages/contact.jsx:123:75)
    at section
    at MyApp (webpack-internal:///./pages/_app.jsx:48:27)
    at ErrorBoundary (webpack-internal:///./node_modules/next/dist/compiled/@next/react-dev-overlay/client.js:8:20638)
    at ReactDevOverlay (webpack-internal:///./node_modules/next/dist/compiled/@next/react-dev-overlay/client.js:8:23179)
    at Container (webpack-internal:///./node_modules/next/dist/client/index.js:323:9)
    at AppContainer (webpack-internal:///./node_modules/next/dist/client/index.js:825:26)
    at Root (webpack-internal:///./node_modules/next/dist/client/index.js:949:27)

React 18 StrictMode issue

There is an issue with React 18 in StrictMode. "Only one captcha is permitted per parent container. " error appears in console
Here is sandbox

Update to react hook

I want create a pull request with the updated version of react. Using React Hooks instead class.

Test keys suddenly stopped working on localhost

The test keys here suddenly stopped working on localhost today across all my projects.

Please see the attached screenshots. The error text at the top of the component is new, and now if I click the checkbox the component gets stuck loading.

Has there been a regression?

Screen Shot 2022-06-07 at 6 58 13 pm

Screen Shot 2022-06-07 at 7 03 09 pm

Feature request - async/await for submitting invisible captchas

It would be great to trigger invisible captchas in a way that returns a promise. It would then make the JS for submitting forms much easier.

This is how you currently need to use invisible captchas:

const Form = () => {
    const captchaRef = useRef<HCaptcha>(null)

    const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault()
        // validate logic
        captchaRef.current?.execute()
    }

    const submitWithToken = (token: string) => {
        // actual submit logic
    }
    return (
        <form onSubmit={handleSubmit}>
            <HCaptcha ref={captchaRef} onVerify={submitWithToken} />
            {/* other form elements */}
        </form>
    )
}

It can be simplified to this with async/await:

const Form = () => {
    const captchaRef = useRef<HCaptcha>(null)

    const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault()
        // validate logic
        const token = await captchaRef.current?.execute()
        // actual submit logic
    }

    return (
        <form onSubmit={handleSubmit}>
            <HCaptcha ref={captchaRef} />
            {/* other form elements */}
        </form>
    )
}

It will make the flow of logic much simpler.

Expose public methods through component

Since certain methods on the hCaptcha API work by passing in the captcha ID, these methods should also be exposed via the react component. Where the methods will proxy to the API, passing in the components ID to each method.

Methods

  • getResponse
  • getRespKey
  • setData

Example Interaction

hcaptchaRef.current.getResponse();

Invisible hCaptcha, React.js

The documentation says that you can watch a demo of invisible captcha using react.
Where is the demo link?
I can't find it.

I added size = "invisible"
But captcha isn't called when the form is submitted

"Please refer to the demo for examples of basic usage and an invisible hCaptcha."

TSC error TS2515

I have this error after TS checking:

$ tsc --noemit
node_modules/@hcaptcha/react-hcaptcha/types/index.d.ts:30:15 - error TS2515: Non-abstract class 'HCaptcha' does not implement inherited abstract member 'render' from class 'Component<HCaptchaProps, HCaptchaState>'.

Doesn't work with preact or preact/compat

See title.

I'm trying to convert my react application to preact, which will significantly reduce my app's bundle size. In my case, it would reduce my initial vendor bundle size by 30%, a significant decrease on my largest necessary file.

Everything else works fine, except that hcaptcha doesn't render.

Unfortunately, there's no error output. I believe react/preact issues usually have to do with lifecycles and re-rendering, but I can't be sure.

Wish I could provide more info. I am using preact/compat, not base preact, so in theory, everything that works with react should just work out of the box, no changes needed. So far, this has the case, except with the hcaptcha component.

I'm sure it's probably something minor and easily fixable, happy to help with debugging if it's useful?

Below are screenshots of what I'm seeing react vs preact

localhost login page with no preact aliases. just normal react
Screen Shot 2020-06-19 at 11 15 08 PM

localhost login page with react packages aliased to preact/compat. No other changes. Hcaptcha doesn't load
Screen Shot 2020-06-19 at 11 12 15 PM

Doesn't work with typescript?

yarn run v1.22.18
$ tsc && vite build
src/App.tsx:10:17 - error TS2607: JSX element class does not support attributes because it does not have a 'props' property.

10                 <Cap
                   ~~~~
11                     sitekey="xyz"
   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
12                     // onVerify={(token: any, ekey: any) => handleVerificationSuccess(token, ekey)}
   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
13                 />
   ~~~~~~~~~~~~~~~~~~

src/App.tsx:10:18 - error TS2786: 'Cap' cannot be used as a JSX component.
  Its instance type 'HCaptcha' is not a valid JSX element.
    Type 'HCaptcha' is missing the following properties from type 'ElementClass': render, context, setState, forceUpdate, and 3 more.

10                 <Cap
                    ~~~


Found 2 errors in the same file, starting at: src/App.tsx:10

error Command failed with exit code 2.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

To reproduce create a new react typescript project using vite and add Hcaptcha component. I followed typescript advice but it doesn't work.

HCaptcha Causes Too Many Re-renders Crash

Details

I have a page that fetches data from some API. For some reason, this page works absolutely fine, complete with its form fields, without HCaptcha. But whenever I put it in, React says it's causing too many re-renders.

The flow is simple, I use a useEffect() hook to fetch the data, and once I get that, render the page - by that I mean I set the loading state to false from its initial value of true. Nothing fancy about it but it was functional.

For added context, I was able to get this working in a smaller contact form page. And I've been trying to isolate and recreate this issue with a fresh project, but to no success. I'll update this post with a sandbox whenever I figure out how to recreate the issue. For now it's quite baffling to say the least, my only fix is to not use HCaptcha, but that obviously defeats the purpose of having a captcha in the first place.

Files are using CRLF newlines and no EOF newline

> file src/index.js
src/index.js: ASCII text, with CRLF line terminators

This is bad because:

  • CRLF <-> LF changes caused by editors on Unix/MacOS machines cause 100% diffs even when changing only a single line (big problem)
  • EOF newline is added by most editors and is the standard (minor nuisance)

Add CI/CD and tests

  • CI pipeline (github actions)
  • CD pipeline (github actions)
  • unit tests (jest)

Add missing callbacks

We want to add the missing callbacks to the React wrapper, see documentation.

  • open-callback
  • close-callback
  • chalexpired-callback

Expected Example:

<HCaptcha 
  onOpen={handleOpen}
  onClose={handleClose}
  onChalExpired={handleChallengeExpired}
/>

Random widget id breaks SSR React apps (Including NextJS)

When using a CSR/SSR hybrid react app (like with the extremely popular NextJS), the randomness of the id breaks the page due to mismatched renders:

Warning: Prop `id` did not match. Server: "hcaptcha-abc" Client: "hcaptcha-xyz"

My suggested fix is to allow the user to optionally pass id as a prop that would take precedence over the nanoId() function currently used to generate the widget id.

Hello, I've just created a hCaptcha Go middleware

Hello contributors, @alikoneko, @brdlyptrs

I know this may not be the right place to ask but I couldn't find other repository to do it.

I've just pushed the https://github.com/kataras/hcaptcha repository which is the first hCaptcha web server's middleware for Go developers. My question is, do you have a place/page that developers can find their hCaptcha clients depending on the programming language they use e.g. at https://docs.hcaptcha.com/ or somewhere else so I can put this package on?

Thanks,
Gerasimos Maropoulos. Author of the Iris Web Framework

captchaRef.current.execute() results in type error (Typescript)

So I'm following one of the examples in the Readme for programmatically invoking hcaptcha.

https://codesandbox.io/s/react-hcaptchaform-example-forked-ngxge?file=/src/Form.jsx

And while the program works, the line captchaRef.current.execute() results in the following type error:

Property 'execute' does not exist on type 'never'.ts(2339)

Any ideas? I've installed the appropriate type files from Definitely Typed.

  • React 16.13.1
  • Next JS 9.5.2
  • Typescript 4.0.2 (strict mode)
  • @hcaptcha/react-hcaptcha 0.2.1

Here's a brief overview of the code:

function Form() {
    const captchaRef = useRef(null)
    const onSubmit = () => captchaRef.current.execute()
    return (
        <form method="post" onSubmit={onSubmit}>
            <HCaptcha sitekey={.....} ref={captchaRef} />
            <button type="submit">Submit</button>
        </form>
    )
}

There's lots of other code as well, but this is enough to produce the type error on my end.

Component completely broken when attempting to render in NextJS

Hello,

I am using this library and we have been using it in next.js, and until today it worked fine, but now it is failing to build out right and is just dragging out a bunch of errors. It appears to be something with the react component.

image
image

Please get back to me on this as soon as you can!

"Rate limited or network error. Please try again." after upgrading from 0.2.2 to 0.3.0

I upgraded the library from 0.2.2 and 0.3.0 and I now get the following error message:

image

I tried to look at this GitHub for documentation on a potential breaking change, but I couldn't find anything. The only tags are 0.3.0-alpha and 0.3.0. Where are the other tags?

I also get the following error log in the dev console:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://hcaptcha.com/checksiteconfig?host=localhost&sitekey=00000000-0000-0000-0000-000000000000&sc=1&swa=1. (Reason: CORS header “Access-Control-Allow-Origin” missing).

How can I fix this issue? Let me know if you need more information.

Cannot adjust width of iframe [button]

As declared in the docs the sizes available are ["normal", "compact", "invisible"] but nothing is mentioned about styling the component e.g adjusting the size of the captcha.

The scenario that I am into is that I want to fill 100% width of a specific container but limited to adjusting the sizes.

I have tried overriding the anchor-content class width but it is being cut because the iframe width should be changed as well.

TypeScript support

Would you be open to accepting a PR to turn this into a TS project? If not, I'll go ahead and submit the types to DefinitelyTyped.

Thanks!

render null next.js

Im Using Next.js version 9.5.5

when using hCaptcha in the console it prints [hCaptcha] render: invalid container 'null' im not sure what the cause might be?

[hCaptcha] render: invalid container 'null'.

hCaptcha is not a rendering giving an error "[hCaptcha] render: invalid container 'null'".

Browser - Chrome (v87.0.4280.141)
Technologies -
Gatsby
Styled-components

{/* Fails to render */}
<Contact id='contact'>
      <Container>
        <Form name='contact' onSubmit={handleSubmit}>
          <FormHeading>Get in touch!</FormHeading>
          {error && <Error>{error}</Error>}
          <Field>
            <Input
              type='text'
              placeholder='Your Name'
              name='name'
              onChange={handleChange('name')}
              required
            />
            <Label>Name</Label>
            <span />
          </Field>
          <Field>
            <Input
              type='email'
              placeholder='[email protected]'
              name='email'
              onChange={handleChange('email')}
              required
            />
            <Label>Email</Label>
            <span />
          </Field>
          <Field>
            <Textarea
              rows={5}
              placeholder='Enter your message here...'
              name='message'
              onChange={handleChange('message')}
              required
            />
            <Label>Message</Label>
            <span />
          </Field>
         {/* Field is a div tag */}
          <Field>
            <HCaptcha
              ref={hCaptchaRef}
              sitekey={process.env.GATSBY_SITE_RECAPTCHA_KEY}
              onVerify={handleCaptchaSuccess}
              onExpire={handleCaptchaExpire}
              onError={handleCaptchaError}
              theme='dark'
            />
          </Field>
          <SubmitBtn type='submit'>Send</SubmitBtn>
        </Form>
      </Container>
 </Contact>

it only works after wrapping it in a form tag without any sibling. The nesting of the form tag is also not valid I guess.

{/* Works */}
<Contact id='contact'>
      <Container>
        <Form name='contact' onSubmit={handleSubmit}>
          <FormHeading>Get in touch!</FormHeading>
          {error && <Error>{error}</Error>}
          <Field>
            <Input
              type='text'
              placeholder='Your Name'
              name='name'
              onChange={handleChange('name')}
              required
            />
            <Label>Name</Label>
            <span />
          </Field>
          <Field>
            <Input
              type='email'
              placeholder='[email protected]'
              name='email'
              onChange={handleChange('email')}
              required
            />
            <Label>Email</Label>
            <span />
          </Field>
          <Field>
            <Textarea
              rows={5}
              placeholder='Enter your message here...'
              name='message'
              onChange={handleChange('message')}
              required
            />
            <Label>Message</Label>
            <span />
          </Field>
          <form>
            <HCaptcha
              ref={hCaptchaRef}
              sitekey={process.env.GATSBY_SITE_RECAPTCHA_KEY}
              onVerify={handleCaptchaSuccess}
              onExpire={handleCaptchaExpire}
              onError={handleCaptchaError}
              theme='dark'
            />
          </form>
          <SubmitBtn type='submit'>Send</SubmitBtn>
        </Form>
      </Container>
 </Contact>

Creating a 2nd Captcha before the API scripts loads causes 2nd script to load

This is best explained by an example:

  1. User is on Page A which has a Captcha A
  2. Captcha A mounts, putting an API script tag on the page.
  3. User Navigates to Page B which has a Captcha B
  4. Captcha B resets the captchaScriptCreated flag, then mounts which places another API script tag on the page.

This is most prevalent in scenarios where the user has a slow connection. I have also created a scenario to test this out there here.

Expected Behavior

API script should only attempt to be loaded once.

Current Behavior

API script is loaded more than once.

Possible Solution

Remove the check from the constructor here, and instead update this line to be

const captchaScriptCreated = typeof hcaptcha !== 'undefined';

Workaround

Load the script with a <script> tag before your page loads.

Hcaptcha Widget Does not Render After Refresh

When I refresh the react page that i'm using this hcaptcha widget on, the hcaptcha fails to rerender until I do a hard refresh (Shift-F5). I'm using typescript if that has anything to do with it.

Language doesn't change

If someone enters a website and a default language is used to load and render the widget, if the visitor then selects another language the widget is re-rendered with a new languageOverride attribute but since the script was already requested in the default language before it won't load the new one and will still be displayed in a language the user doesn't understand.

The widget should be sensitive to language changes or maybe request individual dictionaries from the server in order to re-render in the correct language.

NextJs leads to An unexpected error has occurred.

image

This is what happens after:

yarn build ;
yarn start ;

using the starter here: https://nextjs.org/learn/basics/create-nextjs-app
using this as the index.js:

import Head from 'next/head'
import HCaptcha from '@hcaptcha/react-hcaptcha';

export default () => {
  const handleVerificationSuccess = (token) => {
    console.log(token)
  }

  return (
    <div>
      <HCaptcha
        sitekey="YOUROWNSITEKEYMAN"
        onVerify={token => handleVerificationSuccess(token)}
      />
    </div>
  )
}

and package.json

{
  "name": "learn-starter",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start"
  },
  "dependencies": {
    "@hcaptcha/react-hcaptcha": "^0.1.9",
    "next": "9.3.5",
    "react": "16.13.1",
    "react-dom": "16.13.1"
  }
}

Why is that? ;(

Console errors in the browser are:

TypeError: Cannot read property 'appendChild' of null
    at t.value (index.js:1)
    at co (framework.0f140d5eb2070c7e423d.js:1)
    at Cu (framework.0f140d5eb2070c7e423d.js:1)
    at t.unstable_runWithPriority (framework.0f140d5eb2070c7e423d.js:1)
    at $l (framework.0f140d5eb2070c7e423d.js:1)
    at Su (framework.0f140d5eb2070c7e423d.js:1)
    at du (framework.0f140d5eb2070c7e423d.js:1)
    at ou (framework.0f140d5eb2070c7e423d.js:1)
    at Yu (framework.0f140d5eb2070c7e423d.js:1)
    at framework.0f140d5eb2070c7e423d.js:1
lo @ framework.0f140d5eb2070c7e423d.js:1
main-91963396e6efd93d12cc.js:1 TypeError: Cannot read property 'appendChild' of null
    at t.value (index.js:1)
    at co (framework.0f140d5eb2070c7e423d.js:1)
    at Cu (framework.0f140d5eb2070c7e423d.js:1)
    at t.unstable_runWithPriority (framework.0f140d5eb2070c7e423d.js:1)
    at $l (framework.0f140d5eb2070c7e423d.js:1)
    at Su (framework.0f140d5eb2070c7e423d.js:1)
    at du (framework.0f140d5eb2070c7e423d.js:1)
    at ou (framework.0f140d5eb2070c7e423d.js:1)
    at Yu (framework.0f140d5eb2070c7e423d.js:1)
    at framework.0f140d5eb2070c7e423d.js:1
(anonymous) @ main-91963396e6efd93d12cc.js:1

Does this means that NextJs pretty sucks? Cause I have seen this error in other places as well. Seems like I have to switch? Should I do the switch? to Gatsby? Cause I NEED SGS.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.