jscul
jscul

Reputation: 772

Google reCaptcha to work in React.js?

I'm getting so close... loading the element in is fine EXCEPT for the fact that something in the way the reCaptcha script works makes it so that rendering isn't done when you create an instance of the 'g-recaptcha' class. SO. The reCaptcha WILL load (every time/functionally correct) if I use...

// the div that contains the reCaptcha is in < Contact / >
ReactDOM.render( < Contact / > , document.getElementById('non-header'));

// adding another recaptcha/api.js to the head
var imported = document.createElement('script');
imported.src = 'https://www.google.com/recaptcha/api.js';
document.head.appendChild(imported);

This is clearly a horrendous solution as every time 'Contact' is loaded another script is appended to the head. Not only that... there's already a reCaptcha script I put in the head in the initial document (this is just re-instigating it over and over). Using the libraries API and resetting the reCaptcha doesn't work (see below)...

ReactDOM.render( < Contact / > , document.getElementById('non-header'));

//var imported = document.createElement('script');
//imported.src = 'https://www.google.com/recaptcha/api.js';
//document.head.appendChild(imported);

grecaptcha.reset();


74:2  error  'grecaptcha' is not defined  no-undef !!!

So somehow I need to access the script methods for the reCaptcha div within React. Contact.js is an incredibly basic React component. It may as well just be...

import React, { Component } from 'react';
import './css/Contact.css';

class Contact extends Component {
    render() {
        return (
            <div className='g-recaptcha' id='recaptcha' data-sitekey='******************************'></div>
        );
    }
}

Maybe even just getting an idea of the proper way to include 3rd party scripts in a React Component would help a lot if anyone can provide me some guidance.

Does this seem to be on the right trail (link: https://discuss.reactjs.org/t/using-external-script-libraries/2256)?

Upvotes: 12

Views: 27452

Answers (1)

Vahap Gencdal
Vahap Gencdal

Reputation: 2055

You can use https://github.com/appleboy/react-recaptcha

This library works fine. Here's the usage:

<Recaptcha sitekey="" 
    render="explicit" 
    hl={"ja"} 
    onloadCallback={} 
    verifyCallback={*} />

Upvotes: 2

Related Questions