|
| 1 | +"use strict"; |
| 2 | +var React = require("react"); |
| 3 | +var PropTypes = React.PropTypes; |
| 4 | + |
| 5 | +var ReCAPTCHA = React.createClass({ |
| 6 | + displayName: "react-reCAPTCHA", |
| 7 | + propTypes: { |
| 8 | + sitekey: PropTypes.string.isRequired, |
| 9 | + onChange: PropTypes.func.isRequired, |
| 10 | + onloadCallbackName: PropTypes.string.isRequired, // Name on the script tag onload query parameter |
| 11 | + theme: PropTypes.oneOf(["dark", "light"]), |
| 12 | + type: PropTypes.oneOf(["image", "audio"]), |
| 13 | + tabindex: PropTypes.number, |
| 14 | + onLoad: PropTypes.func, |
| 15 | + onExpired: PropTypes.func, |
| 16 | + }, |
| 17 | + |
| 18 | + getDefaultState: function () { |
| 19 | + return {}; |
| 20 | + }, |
| 21 | + |
| 22 | + getDefaultProps: function () { |
| 23 | + return { |
| 24 | + theme: "light", |
| 25 | + type: "image", |
| 26 | + tabindex: 0, |
| 27 | + elementId: "react-reCAPTCHA", |
| 28 | + }; |
| 29 | + }, |
| 30 | + |
| 31 | + getValue: function () { |
| 32 | + if (typeof grecaptcha !== "undefined" && this.state.widgetId) { |
| 33 | + return grecaptcha.getResponse(this.state.widgetId); |
| 34 | + } |
| 35 | + return null; |
| 36 | + }, |
| 37 | + |
| 38 | + reset: function () { |
| 39 | + if (typeof grecaptcha !== "undefined" && this.state.widgetId) { |
| 40 | + grecaptcha.reset(this.props.widgetId); |
| 41 | + } |
| 42 | + }, |
| 43 | + |
| 44 | + handleExpired: function () { |
| 45 | + if (this.props.onExpired) { |
| 46 | + this.props.onExpired(); |
| 47 | + } else if (this.props.onChange) { |
| 48 | + this.props.onChange(null); |
| 49 | + } |
| 50 | + }, |
| 51 | + |
| 52 | + explicitRender: function () { |
| 53 | + var id = grecaptcha.render(this.refs.captcha.getDOMNode(), { |
| 54 | + sitekey: this.props.sitekey, |
| 55 | + callback: this.props.onChange, |
| 56 | + theme: this.props.theme, |
| 57 | + type: this.props.type, |
| 58 | + tabindex: this.props.tabindex, |
| 59 | + "expired-callback": this.handleExpired, |
| 60 | + }); |
| 61 | + this.setState({ |
| 62 | + widgetId: id, |
| 63 | + }); |
| 64 | + }, |
| 65 | + |
| 66 | + |
| 67 | + handleLoad: function () { |
| 68 | + this.explicitRender(); |
| 69 | + if (this.props.onLoad) { |
| 70 | + this.props.onLoad(); |
| 71 | + } |
| 72 | + }, |
| 73 | + |
| 74 | + componentDidMount: function () { |
| 75 | + // If script is not loaded, set the callback on window. |
| 76 | + if (typeof grecaptcha === "undefined") { |
| 77 | + window[this.props.onloadCallbackName] = this.handleLoad; |
| 78 | + } else { |
| 79 | + this.handleLoad(); |
| 80 | + } |
| 81 | + }, |
| 82 | + |
| 83 | + render: function () { |
| 84 | + return ( |
| 85 | + <div ref="captcha" id={this.props.elementId} /> |
| 86 | + ); |
| 87 | + } |
| 88 | +}); |
| 89 | + |
| 90 | +module.exports = ReCAPTCHA; |
0 commit comments