Skip to content

Instantly share code, notes, and snippets.

@kykean
Created July 30, 2018 09:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kykean/29edc055e75a39bdcd329d3323f8bf0b to your computer and use it in GitHub Desktop.
Save kykean/29edc055e75a39bdcd329d3323f8bf0b to your computer and use it in GitHub Desktop.
Recaptcha script on demand loading with react
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