Kuanysh Bayandinov

Async non-blocking Stripe.js in React

Loading Stripe.js with the usual

<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:

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

Get updates via email or RSS.

Cancel anytime. No obligations.