Created
June 2, 2019 21:09
-
-
Save nickdandakis/87159d4eb9dd7a95035d54050b6d1550 to your computer and use it in GitHub Desktop.
A React component for Google's ReCAPTCHA
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react'; | |
import PropTypes from 'prop-types'; | |
class ReCAPTCHA extends Component { | |
static propTypes = { | |
sitekey: PropTypes.string.isRequired, | |
onVerify: PropTypes.func, | |
}; | |
static defaultProps = { | |
onVerify: () => {}, | |
}; | |
static isReady() { | |
return typeof window !== 'undefined' && typeof window.grecaptcha !== 'undefined'; | |
} | |
componentDidMount() { | |
if (ReCAPTCHA.isReady()) { | |
this.renderOnReady(); | |
} else { | |
this.renderOnReadyInterval = setInterval(this.renderOnReady, 500); | |
} | |
} | |
componentWillUnnmount() { | |
if (this.renderOnReadyInterval) { | |
clearInterval(this.renderOnReadyInterval); | |
} | |
} | |
renderOnReady = () => { | |
if (ReCAPTCHA.isReady() && !this.renderedEl) { | |
this.renderReCAPTCHA(); | |
} else if (ReCAPTCHA.isReady()) { | |
clearInterval(this.renderOnReadyInterval); | |
} | |
} | |
renderReCAPTCHA() { | |
const { sitekey, onVerify } = this.props; | |
try { | |
this.renderedEl = window.grecaptcha.render(this.$el, { | |
sitekey, | |
callback: onVerify, | |
}); | |
} catch (error) { | |
if (error.message !== 'reCAPTCHA has already been rendered in this element') { | |
throw error; | |
} | |
// no-op if ReCAPTCHA already rendered (server-side render bug) | |
} | |
} | |
render() { | |
const { sitekey } = this.props; | |
return ( | |
<div | |
className="g-recaptcha" | |
data-sitekey={sitekey} | |
ref={(el) => { this.$el = el; }} | |
/> | |
); | |
} | |
} | |
export default ReCAPTCHA; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment