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

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!

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.

CrowdforJobs is an advanced hiring platform based on artificial intelligence, enabling recruiters to hire top talent effortlessly.

CrowdforJobs

CrowdforApps brings to you the well researched list of the most successful and finest App development companies, Web software developers.

CrowdforApps

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
CFT

News & Blogs

a7dde0c88b2c61976c79d9ce5b33f2dc.jpg

How to Import Components from React Bootstrap

React Bootstrap is one of the broadly utilized libraries in React, and its different parts are ut...

37af18311d4697c1cb6b46890f15fa40.png

Do you need a React framework?

Inspiration  Respond is a JavaScript library for building UIs, yet when we need to create a...

4c7562e50ce96ee49cf3bf3e8efe935b.png

How to write if statement in React.js?

Obviously, in the event that we consider if proclamation in Javascript or Typescript rationale, i...

Top Authors

Hey, I am Suraj - a full-time blogger and a social media expert currently working on the Growth H...

Suraj Kumar

Overall 3+ years of experience as a Full Stack Developer with a demonstrated history of working i...

Lokesh Gupta

With good communication and writing skiils, Astha Sharma is a full-time content writer working wi...

Astha Sharma

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

Zakariya Usman
CFT

Our Client Says

WhatsApp Chat with Our Support Team