Home ยป ReactJS - Google ReCaptcha v3 example

ReactJS-Google ReCaptcha v3 example

In this article, I’m going to explain how to implement google ReCaptcha V3 in react application, The latest v3 is different than v2, it doesn’t require user interaction. if you want to implement google ReCaptcha v2 check this article.

in this post, we learn how to implement google ReCaptcha V3 in react, which is owned and maintained by Google, we will use the react-google-recaptcha-v3 npm package for implementation.

You can download the working example of the ReCaptcha component on Github – Google ReCaptcha V3 Example

Create a React application

Create a React app using the below command.

 npx create-react-app react-google-recaptcha-v3-example

The above command will create a new folder with the app name so you need to move into that folder, use the below command to change the directory.

 cd react-google-recaptcha-v3-example

Generating keys for google ReCaptcha

Open the https://www.google.com/recaptcha/admin/ The captcha registration will look like this

google recaptcha v3 example

Select the ReCaptcha type V3, because this tutorial will explain the reCAPTCHA V3, Fill out the rest of the form and submit the form like domain, and label name. After submitting the form you will redirect to the next page where you can find the Site Key and Secret keys for google Recaptcha.

React Google Recaptcha V3

Copy the Site Key by clicking on the COPY SITE KEY link, key will be copied to the clipboard

Install react-google-recaptcha-v3 library

We will use the react-google-recaptcha-v3 npm package for the implement captcha, it is a popular and lightweight npm package for google captcha. so open your terminal window and run the below command.

 npm i react-google-recaptcha-v3 --save

Add code to the file

Create a component file GoogleRecaptchaComponent.js for the showcase of the captcha example, in this example, I am just explaining about captcha so I have put code for captcha only.

import React, { useCallback, useEffect, useState } from "react";
import 'bootstrap/dist/css/bootstrap.css';
import { Form, Button, Col } from "react-bootstrap";

import {
    GoogleReCaptchaProvider,
    useGoogleReCaptcha
} from 'react-google-recaptcha-v3';

const GoogleRecaptchaComponent = () => {
    const { executeRecaptcha } = useGoogleReCaptcha();
    const [token, setToken] = useState('');
    const [actionToChange, setActionToChange] = useState('');

    const registerUser = useCallback(async () => {
        if (!executeRecaptcha) {
            return;
        }
        const result = await executeRecaptcha('register');
        setToken(result);
    }, [executeRecaptcha]);

    const handleTextChange = useCallback(event => {
        setActionToChange(event.target.value);
    }, []);

    useEffect(() => {
        if (!executeRecaptcha) {
            return;
        }
        const handleReCaptchaVerify = async () => {
            const token = await executeRecaptcha('register');
            setToken(token);
        };
        handleReCaptchaVerify();
    }, [executeRecaptcha]);

    return (
        <div>
            <div className="row d-flex justify-content-center text-center">
                <h1>React Google Recaptcha V3 example - technostuf.com</h1>
                <hr />
                <Col xs={6}>
                    <Form>
                        <Form.Group className="mb-3" controlId="firstName">
                            <Form.Label>First Name</Form.Label>
                            <Form.Control type="text" placeholder="First name" onChange={handleTextChange} value={actionToChange} />
                        </Form.Group>

                        <Form.Group className="mb-3" controlId="lastName">
                            <Form.Label>Last Name</Form.Label>
                            <Form.Control type="text" placeholder="Last Name" />
                        </Form.Group>
                        <Button variant="primary" type="button" onClick={registerUser}>
                            Submit
                        </Button>
                    </Form>
                </Col>
            </div>
            {token && <p>Token: {token}</p>}
        </div>
    );
}
export default GoogleRecaptchaComponent;

How it works

  1. The end-user request or visits a web page.
  2. The server or website returns the page you requested, While rendering a page react call the useEffect method.
  3. in useEffect method, executeRecaptcha() will generate the token, executeRecaptcha method require an action to be passed to generate a token for every action.
  4. After generating the token we have set the state for the token so we can use it globally in the component.
  5. Now you have to send this token to server-side to verify the token, here is the sample code to verify the server-side(NodeJS).
let captchaToken = req.body.captchaToken;
// Call Google's API to get score
const res = await axios.post(
  `https://www.google.com/recaptcha/api/siteverify?secret=${YOUR_PRIVATE_KEY}&response=${captchaToken}`
);

// Extract result from the API response
if (res.data.success){
  console.log('Valid');
} else {
  console.log('Invalid');
}

Finally, you have to import GoogleRecaptchaComponentinto App.js

import './App.css';
import GoogleRecaptchaComponent from './GoogleRecaptchaComponent';

import {
  GoogleReCaptchaProvider,
  useGoogleReCaptcha
} from 'react-google-recaptcha-v3';

function App() {
  return (
    <div className="App">
      <GoogleReCaptchaProvider reCaptchaKey="[Your recaptcha key]">
        <GoogleRecaptchaComponent />
      </GoogleReCaptchaProvider>
    </div>
  );
}

export default App;

Run a React application

Run the React application using the following command.

 npm start

After compilation, the program opens your browser and runs http://localhost:3000/

Output

You can download the working example.

Github – Google ReCaptcha V3 Example

Related Post

Leave a Comment

Your email address will not be published.

fifteen − 13 =