Google reCaptcha to work in React.js?

I get so close ... loading an element in EXCEPT order because something in the way the reCaptcha script works does it so that the rendering is not executed when you create an instance of 'g-recaptcha'. SO. ReCaptcha will load (every time / functionally correctly) 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 terrifying decision, as each time a Contact is loaded, another script is added to the head. And not only that ... there is already a reCaptcha script that I inserted into the head in the original document (it just repeats it again and again). Using the library APIs and resetting reCaptcha does not 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 inside React. Contact.js is an incredibly basic React component. It could 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> ); } } 

Perhaps even just getting an idea of ​​the correct way to incorporate third-party scripts into the React component will help a lot if someone can provide me some recommendations.

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

+9
source share
2 answers

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

The library is working fine

Using:

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

For those who are looking for this thread and do not want to use a third-party library, I proposed the ReCaptcha component with automatic loading, without third-party dependencies, I hope this helps

The bottom line:

https://gist.github.com/ivansnek/8b69055ddef6b6a43769ed95bd7360f8

CodeSandbox:

https://codesandbox.io/embed/patient-shape-k8r1l?fontsize=14

0
source

Source: https://habr.com/ru/post/1264875/


All Articles