|
import * as React from 'react' |
|
import ReCAPTCHA from "react-google-recaptcha"; |
|
|
|
// This is a demo site key provided by google for testing, since recaptcha is domain based. |
|
// 6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI |
|
// Google test secret (for server side verification) -> 6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe |
|
|
|
interface ReCaptchaFormProps { |
|
sitekey: string |
|
children?: React.ReactNode |
|
onSubmitOkay?: (e: any, token: string) => void |
|
className?: string |
|
buttonClass?: string |
|
buttonDisabled?: boolean |
|
buttonText: string |
|
size: "compact" | "normal" | "invisible" |
|
badge?: "bottomright" | "bottomleft" | "inline" |
|
} |
|
|
|
interface ReCaptchaFormState { |
|
token: string |
|
error: string |
|
} |
|
export class ReCaptchaForm extends React.Component<ReCaptchaFormProps, ReCaptchaFormState> { |
|
private recaptchaRef: any |
|
|
|
constructor(props: ReCaptchaFormProps) { |
|
super(props) |
|
this.state = { token: "", error: "" } |
|
this.recaptchaRef = React.createRef() |
|
|
|
this.onReCapthcaChange = this.onReCapthcaChange.bind(this) |
|
this.onSubmitCaptcha = this.onSubmitCaptcha.bind(this) |
|
} |
|
|
|
onReCapthcaChange = (token: string) => { |
|
this.setState(s => ({ ...s, token: token, error: "" })) |
|
} |
|
|
|
onSubmitCaptcha = async (e: React.FormEvent<HTMLFormElement>) => { |
|
e.preventDefault() |
|
|
|
const token = this.props.size != 'invisible' ? this.recaptchaRef.current.getValue() : await this.recaptchaRef.current.executeAsync(); |
|
|
|
if (this.state.token == token && token != "" && this.state.token != "") { |
|
console.log("form submited, you are not a robot") |
|
this.props.onSubmitOkay(e, token) |
|
} else { |
|
this.setState(s => ({ ...s, error: "Please complete the ReCaptcha" })) |
|
} |
|
} |
|
|
|
render() { |
|
return <form onSubmit={this.onSubmitCaptcha} className={this.props.className}> |
|
|
|
{this.props.children} |
|
|
|
{this.state.error != "" && <div>{this.state.error}</div>} |
|
|
|
{/*ReCaptcha component */} |
|
<ReCAPTCHA |
|
ref={this.recaptchaRef} |
|
sitekey={this.props.sitekey} |
|
onChange={this.onReCapthcaChange} |
|
onErrored={() => console.log("ReCaptcha failed")} |
|
onExpired={() => this.setState(s => ({ ...s, token: "" }))} |
|
badge={this.props.badge} |
|
size={this.props.size} |
|
type="image" |
|
theme="light" |
|
/> |
|
|
|
<button |
|
className={this.props.buttonClass} |
|
disabled={this.props.buttonDisabled == undefined ? false : this.props.buttonDisabled} |
|
type="submit" |
|
> |
|
{this.props.buttonText} |
|
</button> |
|
|
|
</form> |
|
} |
|
} |
This all uses this npm package https://www.npmjs.com/package/react-google-recaptcha