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> | |
); | |
} | |
} |
Thanks!
This inspired me to write a Hooks version of this component: https://gist.github.com/daviseford/4a0ed622dc47090fe22c1870217d88d6
@daviseford awesome! 🎉
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is can be used in place of the Stripe Elements
StripeProvider
component, to asynchronously load the "stripe.js" file. It takes anapiKey
as the only prop. Make sure in any direct stripe calls, likestripe.createSource(…)
you verify that props.stripe is not null.This is inspired by this Stripe async demo code.