Loading Stripe.js
with the usual
1
<script src="https://js.stripe.com/v3" />
doesn’t work in the context of React. Instead we need to use the
StripeProvider
HOC from Stripe’s
react-stripe-elements.
Loading Stripe.js in server-side rendered mode ended up looking like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import React from 'react'
// additional check for document.body in case of server-side rendering
import { StripeProvider, Elements, CardElement } from 'react-stripe-elements'
// the stripe key you get from the dashboard
const STRIPE_PUBLISHABLE_KEY = 'pk_xxxxxxxxxxxxxxxx'
class BillingPage extends React.Component {
state = {
stripe: null
}
componentDidMount() {
if (window.Stripe) {
this.setStripe()
}
else {
const stripe = document.createElement('script')
stripe.type = 'text/javascript'
stripe.src = 'https://js.stripe.com/v3/'
stripe.async = true
stripe.onload = () => {
setTimeout(this.setStripe, 500)
}
// additional check for document.body in case of server-side rendering
document.body && document.body.appendChild(stripe)
}
}
setStripe = () => this.setState({
stripe: window.Stripe(STRIPE_PUBLISHABLE_KEY)
})
render() {
return (
<StripeProvider stripe={this.state.stripe}>
<Elements>
<CardElement />
</Elements>
</StripeProvider>
)
}
}
export default BillingPage