How to setup Google reCAPTCHA in a ReactJS app?

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.

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 ReactJS

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.

News & Blogs

d8427811a0a733d77e06de028b5f59ca.png

How to Implement MySQL Slow Query Log

ENABLING THE MYSQL SLOW QUERY LOG Slow queries can affect database performance and overall serve...

e58d929bc4999ddd2bd803bd94eb1cac.png

What It Was Like to Write a Full Blown Flutter App

1. Porting an iOS App to Flutter Since my last post about Flutter months ago, I felt that the lo...

f62dbc1a41f2267ac3920998ea272871.jpg

You Don’t Need Loops in JavaScript

1. To Loop Through All Elements and Get an new modified array Using loop: var names = ["Jack",...