google recaptcha

Vite

Integrate the react google recaptcha with Vite

Install the required package using your preferred package manager:

npm install @google-recaptcha/react
pnpm add @google-recaptcha/react
yarn add @google-recaptcha/react
bun add @google-recaptcha/react

Wrap your application with the GoogleReCaptchaProvider in your root component:

// src/main.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { GoogleReCaptchaProvider } from '@google-recaptcha/react'; 

import App from './App';

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <GoogleReCaptchaProvider
      type="v3"
      siteKey="your_site_key"
    >
      <App />
    </GoogleReCaptchaProvider>
  </React.StrictMode>
);

Create a component to use reCAPTCHA:

import type { FormEvent } from 'react';
import { useGoogleReCaptcha } from '@google-recaptcha/react';

export const Form = () => {
  const googleReCaptcha = useGoogleReCaptcha();

  const onSubmit = async (event: FormEvent) => {
    event.preventDefault();

    const token = await googleReCaptcha.executeV3();
    ...
  };

  return (
    <form onSubmit={onSubmit}>
      ...
      <button type="submit">Submit</button>
    </form>
  );
}