├── .gitignore
├── .npmignore
├── .nvmrc
├── .prettierrc
├── LICENCE.md
├── README.md
├── __tests__
├── google-recaptcha-provider.test.tsx
├── tsconfig.json
├── use-google-recaptcha.test.tsx
└── with-google-recaptcha.test.tsx
├── example
├── google-recaptcha-example.tsx
├── index.tsx
└── with-google-recaptcha-example.tsx
├── index.html
├── jest.config.js
├── package-lock.json
├── package.json
├── rollup.config.js
├── src
├── google-recaptcha-provider.tsx
├── google-recaptcha.tsx
├── index.ts
├── use-google-recaptcha.tsx
├── utils.ts
└── with-google-recaptcha.tsx
├── tsconfig.json
├── tslint.json
└── webpack.config.js
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | # Created by https://www.gitignore.io/api/node
3 | # Edit at https://www.gitignore.io/?templates=node
4 |
5 | ### Node ###
6 | # Logs
7 | logs
8 | *.log
9 | npm-debug.log*
10 | yarn-debug.log*
11 | yarn-error.log*
12 |
13 | # Runtime data
14 | pids
15 | *.pid
16 | *.seed
17 | *.pid.lock
18 |
19 | # Directory for instrumented libs generated by jscoverage/JSCover
20 | lib-cov
21 |
22 | # Coverage directory used by tools like istanbul
23 | coverage
24 |
25 | # nyc test coverage
26 | .nyc_output
27 |
28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
29 | .grunt
30 |
31 | # Bower dependency directory (https://bower.io/)
32 | bower_components
33 |
34 | # node-waf configuration
35 | .lock-wscript
36 |
37 | # Compiled binary addons (https://nodejs.org/api/addons.html)
38 | build/Release
39 |
40 | # Dependency directories
41 | node_modules/
42 | jspm_packages/
43 |
44 | # TypeScript v1 declaration files
45 | typings/
46 |
47 | # Optional npm cache directory
48 | .npm
49 |
50 | # Optional eslint cache
51 | .eslintcache
52 |
53 | # Optional REPL history
54 | .node_repl_history
55 |
56 | # Output of 'npm pack'
57 | *.tgz
58 |
59 | # Yarn Integrity file
60 | .yarn-integrity
61 |
62 | # dotenv environment variables file
63 | .env
64 |
65 | # parcel-bundler cache (https://parceljs.org/)
66 | .cache
67 |
68 | # next.js build output
69 | .next
70 |
71 | # nuxt.js build output
72 | .nuxt
73 |
74 | # vuepress build output
75 | .vuepress/dist
76 |
77 | # Serverless directories
78 | .serverless/
79 |
80 | # FuseBox cache
81 | .fusebox/
82 |
83 | #DynamoDB Local files
84 | .dynamodb/
85 |
86 | # End of https://www.gitignore.io/api/node
87 |
88 | dist
89 | build
90 | .rpt2_cache
91 |
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | example
2 | tslint.json
3 | webpack.config.js
4 | index.html
5 | __tests__
6 | jest.config.js
7 | .prettierrc
8 | build
9 | src
10 | .nvmrc
11 | rollup.config.js
12 | tsconfig.json
--------------------------------------------------------------------------------
/.nvmrc:
--------------------------------------------------------------------------------
1 | v14.8.0
2 |
--------------------------------------------------------------------------------
/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "singleQuote": true,
3 | "trailingComma": "none",
4 | "tabWidth": 2,
5 | "arrowParens": "avoid"
6 | }
7 |
--------------------------------------------------------------------------------
/LICENCE.md:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 Duong Tran
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
React Google Recaptcha V3
2 |
3 |
4 | [React](https://reactjs.org/) library for integrating Google ReCaptcha V3 to your App.
5 |
6 | [](https://www.npmjs.com/package/react-google-recaptcha-v3)
7 | 
8 | 
9 |
10 |
11 |
12 | ## Install
13 |
14 | ```bash
15 | npm install react-google-recaptcha-v3
16 | ```
17 |
18 | ## Usage
19 |
20 | #### Provide Recaptcha Key
21 |
22 | To use `react-google-recaptcha-v3`, you need to create a recaptcha key for your domain, you can get one from [here](https://www.google.com/recaptcha/intro/v3.html).
23 |
24 | #### Enterprise
25 |
26 | When you enable to use the enterprise version, **you must create new keys**. These keys will replace any Site Keys you created in reCAPTCHA. Check the [migration guide](https://cloud.google.com/recaptcha-enterprise/docs/migrate-recaptcha).
27 |
28 | To work properly, you **must** select the Integration type to be `Scoring` since is equivalent to the reCAPTCHA v3.
29 |
30 | The complete documentation to the enterprise version you can see [here](https://cloud.google.com/recaptcha-enterprise/docs/quickstart).
31 |
32 | #### Components
33 |
34 | ##### GoogleReCaptchaProvider
35 |
36 | `react-google-recaptcha-v3` provides a `GoogleReCaptchaProvider` provider component that should be used to wrap around your components.
37 |
38 | `GoogleReCaptchaProvider`'s responsibility is to load the necessary reCaptcha script and provide access to reCaptcha to the rest of your application.
39 |
40 | Usually, your application only needs one provider. You should place it as high as possible in your React tree. It's to make sure you only have one instance of Google Recaptcha per page and it doesn't reload unecessarily when your components re-rendered.
41 |
42 | Same thing applied when you use this library with framework such as Next.js or React Router and only want to include the script on a single page. Try to make sure you only have one instance of the provider on a React tree and to place it as high (on the tree) as possible.
43 |
44 | | **Props** | **Type** | **Default** | **Required?** | **Note** |
45 | |----------------------|:----------------:| ----------: | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
46 | | reCaptchaKey | String | | Yes | Your recaptcha key, get one from [here](https://www.google.com/recaptcha/intro/v3.html) |
47 | | scriptProps | Object | | No | You can customize the injected `script` tag with this prop. It allows you to add `async`, `defer`, `nonce` attributes to the script tag. You can also control whether the injected script will be added to the document body or head with `appendTo` attribute. |
48 | | language | String | | No | optional prop to support different languages that is supported by Google Recaptcha. https://developers.google.com/recaptcha/docs/language |
49 | | useRecaptchaNet | Boolean | false | No | The provider also provide the prop `useRecaptchaNet` to load script from `recaptcha.net`: https://developers.google.com/recaptcha/docs/faq#can-i-use-recaptcha-globally |
50 | | useEnterprise | Boolean | false | No | [Enterprise option](#enterprise) |
51 | | container.element | String HTMLElement | | No | Container ID where the recaptcha badge will be rendered |
52 | | container.parameters | Object | | No | Configuration for the inline badge (See google recaptcha docs) |
53 |
54 | ```javascript
55 | import { GoogleReCaptchaProvider } from 'react-google-recaptcha-v3';
56 |
57 | ReactDom.render(
58 |
77 |
78 | ,
79 | document.getElementById('app')
80 | );
81 | ```
82 |
83 | There are three ways to trigger the recaptcha validation: using the `GoogleReCaptcha` component, wrapping your component with the HOC `withGoogleReCaptcha`, or using the custom hook `useGoogleReCaptcha`.
84 |
85 | #### GoogleReCaptcha
86 |
87 | `GoogleRecaptcha` is a react component that can be used in your app to trigger the validation. It provides a prop `onVerify`, which will be called once the verify is done successfully, also supports a prop `refreshReCaptcha` which supports any type of value and is used to force recaptcha to revalidate (you can use a timestamp updated after every submit), there is an example below.
88 |
89 | ```javascript
90 | import {
91 | GoogleReCaptchaProvider,
92 | GoogleReCaptcha
93 | } from 'react-google-recaptcha-v3';
94 |
95 | ReactDom.render(
96 |
97 |
98 | ,
99 | document.getElementById('app')
100 | );
101 | ```
102 |
103 | ```javascript
104 | // IMPORTANT NOTES: The `GoogleReCaptcha` component is a wrapper around `useGoogleRecaptcha` hook and use `useEffect` to run the verification.
105 | // It's important that you understand how React hooks work to use it properly.
106 | // Avoid using inline function for the `onVerify` props as it can possibly cause the verify function to run continously.
107 | // To avoid that problem, you can use a memoized function provided by `React.useCallback` or a class method
108 | // The code below is an example that inline function can result in an infinite loop and the verify function runs continously:
109 |
110 | const MyComponent: FC = () => {
111 | const [token, setToken] = useState();
112 |
113 | return (
114 |
151 | );
152 | };
153 | ```
154 |
155 | #### React Hook: useGoogleReCaptcha (recommended approach)
156 |
157 | If you prefer a React Hook approach over the old good Higher Order Component, you can choose to use the custom hook `useGoogleReCaptcha` over the HOC `withGoogleReCaptcha`.
158 |
159 | The `executeRecaptcha` function returned from the hook can be undefined when the recaptcha script has not been successfully loaded.
160 | You can do a null check to see if it's available or not.
161 |
162 | How to use the hook:
163 |
164 | ```javascript
165 | import {
166 | GoogleReCaptchaProvider,
167 | useGoogleReCaptcha
168 | } from 'react-google-recaptcha-v3';
169 |
170 | const YourReCaptchaComponent = () => {
171 | const { executeRecaptcha } = useGoogleReCaptcha();
172 |
173 | // Create an event handler so you can call the verification on button click event or form submit
174 | const handleReCaptchaVerify = useCallback(async () => {
175 | if (!executeRecaptcha) {
176 | console.log('Execute recaptcha not yet available');
177 | return;
178 | }
179 |
180 | const token = await executeRecaptcha('yourAction');
181 | // Do whatever you want with the token
182 | }, [executeRecaptcha]);
183 |
184 | // You can use useEffect to trigger the verification as soon as the component being loaded
185 | useEffect(() => {
186 | handleReCaptchaVerify();
187 | }, [handleReCaptchaVerify]);
188 |
189 | return ;
190 | };
191 |
192 | ReactDom.render(
193 |
194 |
195 | ,
196 | document.getElementById('app')
197 | );
198 | ```
199 |
200 | #### withGoogleReCaptcha
201 |
202 | `GoogleRecaptcha` is a HOC (higher order component) that can be used to integrate reCaptcha validation with your component and trigger the validation programmatically. It inject the wrapped component with `googleReCaptchaProps` object.
203 |
204 | The object contains the `executeRecaptcha` function that can be called to validate the user action.
205 |
206 | You are recommended to use the custom hook `useGoogleReCaptcha` over the HOC whenever you can. The HOC can be removed in future version.
207 |
208 | ```javascript
209 | import {
210 | GoogleReCaptchaProvider,
211 | withGoogleReCaptcha
212 | } from 'react-google-recaptcha-v3';
213 |
214 | class ReCaptchaComponent extends Component<{}> {
215 | handleVerifyRecaptcha = async () => {
216 | const { executeRecaptcha } = (this.props as IWithGoogleReCaptchaProps)
217 | .googleReCaptchaProps;
218 |
219 | if (!executeRecaptcha) {
220 | console.log('Recaptcha has not been loaded');
221 |
222 | return;
223 | }
224 |
225 | const token = await executeRecaptcha('homepage');
226 | };
227 |
228 | render() {
229 | return (
230 |