hcaptcha / react-hcaptcha Goto Github PK
View Code? Open in Web Editor NEWhCaptcha Component Library for ReactJS and Preact
License: MIT License
hCaptcha Component Library for ReactJS and Preact
License: MIT License
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
localhost login page with react packages aliased to preact/compat. No other changes. Hcaptcha doesn't load
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.
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)
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.
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?
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.
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?
This is best explained by an example:
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.
API script should only attempt to be loaded once.
API script is loaded more than once.
Remove the check from the constructor here, and instead update this line to be
const captchaScriptCreated = typeof hcaptcha !== 'undefined';
Load the script with a <script>
tag before your page loads.
I would like to put Hcaptcha in React native, can you create the project?
Hello, thanks for the package. It seems when there is multiple captchas, only the last one will render. I've tried variations of adding and id
, key
, etc. with no luck.
Am I missing something or is this a bug?
https://codesandbox.io/s/optimistic-pond-0ll6g?file=/src/App.js
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.
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.
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>
I upgraded the library from 0.2.2 and 0.3.0 and I now get the following error message:
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.
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.
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
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>'.
As the title says, Typescript type definitions are missing the eKey
parameter for onVerify
> file src/index.js
src/index.js: ASCII text, with CRLF line terminators
This is bad because:
It happens on SSR.
Node.js version: v12.16.1
We want to add the missing callbacks to the React wrapper, see documentation.
Expected Example:
<HCaptcha
onOpen={handleOpen}
onClose={handleClose}
onChalExpired={handleChallengeExpired}
/>
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.
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.
hcaptchaRef.current.getResponse();
There is an issue with React 18 in StrictMode. "Only one captcha is permitted per parent container. " error appears in console
Here is sandbox
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)
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.
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.
Any idea why this is happening? And this does not happen in my local though.
Would appreciate any help from you all.
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
It seems the current setup for github actions will not be triggered when pull requests are opened from forked repositories. It looks like we need to add pull_request_target
with types [ opened ]
for these to be triggered, see github action docs.
See Issue WordPress/gutenberg#17324
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.
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.
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
I want create a pull request with the updated version of react. Using React Hooks instead class.
the error appeared when i changed the props (like theme
)
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."
i.e.
Line 19 in 796babe
should be:
script.src = "${JSAPI_URI}?render=explicit&onload=hcaptchaOnLoad";
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!
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
.
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.
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.
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?
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.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.