'wait for loading paypal script in nextjs page

I have this code that is supposed to render the PayPal buttons.

    <Head>
      <script src="https://www.paypal.com/sdk/js?client-id=KEY"></script>
    </Head>

I load the PayPal buttons in the componentDidMount method

componentDidMount() {
    paypal
.Buttons({
  createOrder: (data, actions)=> {
    return actions.order.create({
      purchase_units: [{
          amount: {
            currency_code: "USD",
            value: amount,
          },
        }],
    });
  },
  onCancel: function(data){
    //console.log(data)

  },
  onError: function(err){
    console.log(err)
  }
})
.render("#paypal");
 }




<div id="paypal" className=""></div>

on the first page load, the page throws an error that PayPal is not defined I am guessing because the script is not loaded fully when the componentDidMount method is called. How can I wait until the script is loaded for the buttons to be rendered properly?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source