YouTube Icon

How to setup Google reCAPTCHA in a ReactJS app?




How to setup Google reCAPTCHA in a ReactJS app?

Google’s reCAPTCHA is an industry standard when it comes to fighting bots. Integrating it in a regular web app has almost become a no-brainer, thanks to plugins available on almost every platform to do the job. With this expectation, I started integrating it in my latest app built on ReactJS but encountered many roadblocks. Without going into details, I’m sharing here fastest recipe for integrating it with your ReactJS app.

When there was a need to integrate google recaptcha to our react app, we had hard times finding the best solution that will fit to all of our needs. We decided to create a new library that will give more freedom, be more flexible, and be easy to use simultaneously. We are Codeep team and this is the guide of how to use `react-recaptcha-google` in your projects.

Learn ReactJS

Currently, we are using ReCaptcha V2 here. ReCaptcha V3 is still in beta version; we will update our component when they release the stable version.

Also Read:- 9 Things for Beginner About ReactJS

Installation

Using npm:

npm install react-recaptcha-google --save

Using yarn:

yarn add react-recaptcha-google

How to use?

The component consists of two main parts?—?initializing and integrating.

1. Initialize the ReCaptcha?—?loadReCaptcha()

This function should be imported and called in the main (parent) component of your app. We recommend calling it in componentDidMount() of App.js.

import { loadReCaptcha } from 'react-recaptcha-google'
...
componentDidMount() {
  loadReCaptcha();
}

After initializing you can use ReCaptcha in all child components without any worries. The advantage of having this function is that you can control when you need to load ReCaptcha and when you want prevent additional calls, e.g. disable ReCaptcha locally.

How to Develop a Blog App Using NextJS

2. Integrate?—?add <ReCaptcha/> in particular components

react-recaptcha-google can be used both for visible and invisible recaptcha. The difference between usage is tiny. You can use the visible one in one component and the invisible one in the next easily.

invisible ReCaptcha

Appears on the bottom right of pages using invisible ReCaptcha

Also Read:- What you pick in 2018 : ReactJS vs AngularJS vs VueJS

For testing the invisible ReCaptcha, create a new component with the following code and give it a try! You may see nothing popping up, but it does not mean ReCaptcha is not working. Just open the console and see that it generated a new token, trusting that you are a human :))

import React, { Component } from 'react';
import { ReCaptcha } from 'react-recaptcha-google'
class ExampleComponent extends Component {
  constructor(props, context) {
    super(props, context);
    this.onLoadRecaptcha = this.onLoadRecaptcha.bind(this);
    this.verifyCallback = this.verifyCallback.bind(this);
  }
componentDidMount() {
    if (this.captchaDemo) {
        console.log("started, just a second...")
        this.captchaDemo.reset();
        this.captchaDemo.execute();
    }
  }
onLoadRecaptcha() {
      if (this.captchaDemo) {
          this.captchaDemo.reset();
          this.captchaDemo.execute();
      }
  }
verifyCallback(recaptchaToken) {
    // Here you will get the final recaptchaToken!!!  
    console.log(recaptchaToken, "<= your recaptcha token")
  }
render() {
    return (
      <div>
        {/* You can replace captchaDemo with any ref word */}
        <ReCaptcha
            ref={(el) => {this.captchaDemo = el;}}
            size="invisible"
            render="explicit"
            sitekey="your_site_key"
            onloadCallback={this.onLoadRecaptcha}
            verifyCallback={this.verifyCallback}
        />
        <code>
          1. Add <strong>your site key</strong> in the ReCaptcha component. <br/>
          2. Check <strong>console</strong> to see the token.
        </code>
      </div>
    );
  };
};
export default ExampleComponent;

Visible / Normal Recaptcha

Source: https://developers.google.com/recaptcha/

Also Read:- What you pick in 2018 : ReactJS vs AngularJS vs VueJS

For having a visible ReCaptcha, you should make two minor changes on the above-mentioned code.

  1. Replace the size prop value invisible (see the imported ReCaptcha component) with either normal or compact. Those will add a checkbox with 'I am not a robot' label.
  2. Remove this.[captchaRef].execute() lines from your code.

Basically, the code will look like this:

import React, { Component } from 'react';
import { ReCaptcha } from 'react-recaptcha-google'
class ExampleComponent extends Component {
  constructor(props, context) {
    super(props, context);
    this.onLoadRecaptcha = this.onLoadRecaptcha.bind(this);
    this.verifyCallback = this.verifyCallback.bind(this);
  }
componentDidMount() {
    if (this.captchaDemo) {
        console.log("started, just a second...")
        this.captchaDemo.reset();
    }
  }
onLoadRecaptcha() {
      if (this.captchaDemo) {
          this.captchaDemo.reset();
      }
  }
verifyCallback(recaptchaToken) {
    // Here you will get the final recaptchaToken!!!  
    console.log(recaptchaToken, "<= your recaptcha token")
  }
render() {
    return (
      <div>
        {/* You can replace captchaDemo with any ref word */}
        <ReCaptcha
            ref={(el) => {this.captchaDemo = el;}}
            size="normal"
            data-theme="dark"            
            render="explicit"
            sitekey="your_site_key"
            onloadCallback={this.onLoadRecaptcha}
            verifyCallback={this.verifyCallback}
        />
        <code>
          1. Add <strong>your site key</strong> in the ReCaptcha component. <br/>
          2. Check <strong>console</strong> to see the token.
        </code>
      </div>
    );
  };
};
export default ExampleComponent;

Optional props

  • data-theme - you can add theme prop with a value of either "dark" or "light"(default) to control the background theme of the visible ReCaptcha (when size is normal or compact)
  • data-badge - you can send badge prop with one of the following values: bottomright (default), bottomleft, inline. This will allowyou to reposition the ReCaptcha badge.

You’re ready to go! Don’t hesitate to ask questions and contribute!

Also Read:- Uploading files with ReactJS and NodeJS

Learn New Technologies



Author Biography.

Lokesh Gupta
Lokesh Gupta

Overall 3+ years of experience as a Full Stack Developer with a demonstrated history of working in the information technology and services industry. I enjoy solving complex problems within budget and deadlines putting my skills on PHP, MySQL, Python, Codeigniter, Yii2, Laravel, AngularJS, ReactJS, NodeJS to best use. Through Knowledge of UML & visual modeling, application architecture design & business process modeling. Successfully delivered various projects, based on different technologies across the globe.

Join Our Newsletter.

Subscribe to CrowdforThink newsletter to get daily update directly deliver into your inbox.

CrowdforGeeks is where lifelong learners come to learn the skills they need, to land the jobs they want, to build the lives they deserve.

CrowdforGeeks

CrowdforThink is a leading Indian media and information platform, known for its end-to-end coverage of the Indian startup ecosystem.

CrowdforThink

Our mission is "Har Koi Dekhe Video, Har Ghar Dekhe Video, Ghar Ghar Dekhe Video" so we Provide videos related to Tutorials, Travel, Technology, Wedding, Cooking, Dance, Festivals, Celebration.

Apna Video Wala
CFT

News & Blogs

703d9a2733f1fc40f636f9d9cdeff391.png

Best React Libraries That Are Worth Trying In 2023

As per the Stack Overflow survey, React.js was the 2nd most popular web framework after Node...

f6dc0df3856bfe502f41ce4965b0a410.png

How To Deploy Your React Website in 2022!

Different React applications need different arrangement arrangements in view of their case. In th...

4248748df2304b0c9e733eec03bdce2d.png

Higher-Order Components in React

A higher-request component (HOC) is a high level method in React for reusing component rationale....

Top Authors

Lamia Rochdi is the Marketing Manager at Bell Flavors & Fragrances EMEA. A successful family-...

Lamia Rochdi

I’m Mertin Wilson a technician in a camera company and certified expert of different P...

Mertin Wilson

Zakariya has recently joined the PakWheels team as a Content Marketing Executive, shortly after g...

Zakariya Usman

Pankaj Singh is a Senior Digital Marketing Consultant with more than 2 years of experience in SEO...

Pankaj Singh
CFT

Our Client Says

WhatsApp Chat with Our Support Team