google-react-recaptcha-v2
v1.0.2
Published
React component for Google reCAPTCHA
Maintainers
Readme
🛡️ React ReCaptchaV2
A lightweight and developer-friendly React component for rendering an invisible Google reCAPTCHA v2 widget. It supports custom callbacks, localization, badge positioning, and can be triggered programmatically using ref.
✅ Supports TypeScript
✅ Works in development and production environments
✅ Easily integrates with forms or async flows
✅ Minimal and clean API
📦 Installation
npm install google-react-recaptcha-v2
# or
yarn add google-react-recaptcha-v2
# or
yarn add google-react-recaptcha-v2🚀 Getting Started
1. Import the Component
import { ReCaptchaV2, ReCaptchaV2Ref } from "google-react-recaptcha-v2";2. Add the Component to Your Form
import { useRef } from "react";
import { ReCaptchaV2, ReCaptchaV2Ref } from "google-react-recaptcha-v2";
export default function MyForm() {
const recaptchaRef = useRef<ReCaptchaV2Ref>(null);
const handleSubmit = async (e) => {
e.preventDefault();
const token = await recaptchaRef.current?.execute();
// Puedes usar el token aquí
console.log("reCAPTCHA token:", token);
};
return (
<>
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
<ReCaptchaV2
ref={recaptchaRef}
siteKey="YOUR_PRODUCTION_SITE_KEY"
// onSuccess es opcional
/>
</>
);
}🧠 Props
ReCaptchaV2Props
| Prop | Type | Required | Default | Description |
| ----------- | ------------------------------------------- | -------- | --------------- | ------------------------------------------------------------- |
| siteKey | string | ✅ | – | Your production Google reCAPTCHA v2 site key. |
| onSuccess | (token: string) => void | ❌ | – | Callback opcional cuando reCAPTCHA se resuelve exitosamente. |
| onError | () => void | ❌ | – | Callback when reCAPTCHA fails to render or complete. |
| onExpired | () => void | ❌ | – | Called when the token expires before verification. |
| badge | "bottomright" \| "bottomleft" \| "inline" | ❌ | "bottomright" | Position of the reCAPTCHA badge on screen. |
| hl | string | ❌ | – | Language code (e.g., "en", "es") for localization. |
| isDevelop | boolean | ❌ | false | Uses Google's default test key if true ("6LeIxAcTAAAA..."). |
| size | "invisible" \| "normal" \| "compact" | ❌ | invisible | Size of the recaptcha |
🧪 Ref Methods
ReCaptchaV2Ref
| Method | Type | Description |
| --------- | ----------------------- | ------------------------------------------------------ |
| execute | () => Promise<string> | Ejecuta el reto invisible y retorna el token generado. |
| reset | () => void | Resetea el widget y limpia el token actual. |
📌 Examples
🌐 Con idioma personalizado y uso de execute
const recaptchaRef = useRef<ReCaptchaV2Ref>(null);
const handleClick = async () => {
const token = await recaptchaRef.current?.execute();
console.log("Token:", token);
};
<ReCaptchaV2 ref={recaptchaRef} siteKey="YOUR_SITE_KEY" hl="es" />;🧪 Modo desarrollo
const recaptchaRef = useRef<ReCaptchaV2Ref>(null);
const handleClick = async () => {
const token = await recaptchaRef.current?.execute();
console.log("Test token:", token);
};
<ReCaptchaV2 isDevelop ref={recaptchaRef} siteKey="will-be-ignored" />;🧭 Posición personalizada del badge
const recaptchaRef = useRef<ReCaptchaV2Ref>(null);
const handleClick = async () => {
const token = await recaptchaRef.current?.execute();
console.log("Token:", token);
};
<ReCaptchaV2 badge="bottomleft" ref={recaptchaRef} siteKey="YOUR_SITE_KEY" />;🧰 Tips
- The reCAPTCHA will not trigger until you call
execute()manually. - Invisible reCAPTCHA es ideal para validaciones no intrusivas antes de enviar acciones sensibles (ej: formularios, comentarios, eliminar).
- Si necesitas retos visibles, cambia el prop
sizea"normal"o"compact".
🏗️ Arquitectura limpia
La librería está estructurada siguiendo Clean Architecture:
- domain: Interfaces y tipos principales.
- application: Hook/caso de uso para el ciclo de vida y callbacks.
- infrastructure: Servicio para cargar y renderizar el widget/script.
- presentation: Componente React que solo orquesta y delega.
Esto permite fácil mantenimiento, testeo y extensión.
🧪 Test Key for Local Development
Use this key when testing locally (no need to register it):
siteKey = "6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI";📜 License
MIT © Andrés Felipe Hernández Aldana
💡 Credits
Built using:
