Created
July 30, 2018 09:12
-
-
Save kykean/29edc055e75a39bdcd329d3323f8bf0b to your computer and use it in GitHub Desktop.
Recaptcha script on demand loading with react
This file contains hidden or 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 { compose, | |
lifecycle, | |
withHandlers, | |
withState, | |
withStateHandlers, | |
} from 'recompose'; | |
import { scriptExists } from '../Helper'; | |
import { withSpinnerWhileLoading } from '../Spinner'; | |
export const scriptSrc = 'https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit'; | |
export const withReCaptcha = compose( | |
withState('loading', 'setLoading', true), | |
withHandlers({ | |
loaded: ({ setLoading }) => () => setLoading(false) | |
}), | |
lifecycle({ | |
componentWillMount() { | |
window.onloadCallback = this.props.loaded; | |
if (!scriptExists(scriptSrc)) { | |
const script = document.createElement('script'); | |
script.src = scriptSrc; | |
script.async = true; | |
script.defer = true; | |
document.body.appendChild(script); | |
} else { | |
this.props.loaded(); | |
} | |
} | |
}), | |
withSpinnerWhileLoading, | |
); | |
export const withReCaptchaState = compose( | |
withStateHandlers(({ | |
captchaToken = '' | |
}) => ({ | |
captchaToken | |
}), { | |
setCaptchaToken: state => captchaToken => ({ | |
...state, | |
captchaToken, | |
}), | |
clearCaptchaToken: state => () => ({ | |
...state, | |
captchaToken: '', | |
}), | |
}), | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment