Last active
December 8, 2020 14:28
-
-
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
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 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> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@daviseford awesome! 🎉