Skip to content

Instantly share code, notes, and snippets.

@mrcoles
Last active December 8, 2020 14:28
Show Gist options
  • Save mrcoles/8c79595f488f0e334e528163feb23293 to your computer and use it in GitHub Desktop.
Save mrcoles/8c79595f488f0e334e528163feb23293 to your computer and use it in GitHub Desktop.
A react provider abstraction for loading the stripe.js file asynchronously to use with Stripe Elements
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { StripeProvider } from 'react-stripe-elements';
export default class AsyncStripeProvider extends Component {
static propTypes = {
apiKey: PropTypes.string.isRequired
};
// constructor
constructor(props) {
super(props);
this.state = {
stripe: null
};
}
// life-cycle
componentDidMount() {
this._mounted = true;
const { apiKey } = this.props;
const stripeJs = document.createElement('script');
stripeJs.src = 'https://js.stripe.com/v3/';
stripeJs.async = true;
stripeJs.onload = () => {
if (this._mounted) {
this.setState({
stripe: window.Stripe(apiKey)
});
}
};
document.body && document.body.appendChild(stripeJs);
}
componentWillUnmount() {
this._mounted = false;
}
// render
render() {
const { stripe } = this.state;
return (
<StripeProvider stripe={stripe}>
<>{this.props.children}</>
</StripeProvider>
);
}
}
@mrcoles
Copy link
Author

mrcoles commented Sep 26, 2019

@daviseford awesome! 🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment