Skip to content

Instantly share code, notes, and snippets.

@mz026
Created July 24, 2018 02:52
Show Gist options
  • Save mz026/b49744a0e086260cdb19f662dfc3af41 to your computer and use it in GitHub Desktop.
Save mz026/b49744a0e086260cdb19f662dfc3af41 to your computer and use it in GitHub Desktop.
POC of reCAPTCHA with React
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
const SITE_KEY = 'xxxx'
class ReCAPTCHA extends Component {
constructor(props) {
super(props)
this._execute = this._execute.bind(this)
this.state = { isSet: false, elementId: (Math.random() * 100).toString() }
}
componentDidMount() {
let isSet = false
let interval = setInterval(()=> {
console.log('interval')
isSet = this._checkLoaded()
if (isSet) {
this.setState({ isSet: true })
clearInterval(interval)
}
}, 500)
}
_checkLoaded() {
if (!window.grecaptcha) {
return
}
window.grecaptcha.render(this.state.elementId, {
callback: this.props.callback,
sitekey: SITE_KEY,
size: 'invisible'
})
return true
}
_execute() {
window.grecaptcha.execute()
}
render() {
return (
<div onClick={this._execute}>
<div id={this.state.elementId}></div>
{
this.state.isSet ? (
this.props.children
) : null
}
</div>
)
}
}
class App extends Component {
constructor(props) {
super(props)
this._callback = this._callback.bind(this)
}
_callback(token) {
console.log('callback', token)
// login(username, password, token)
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, xxedit <code>src/App.js</code> and save to reload.
</p>
<ReCAPTCHA callback={this._callback}>
<button id='btn'> click me</button>
</ReCAPTCHA>
</div>
);
}
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment