Stripe Elements in NextJS app not showing
P粉458913655
P粉458913655 2023-09-17 00:22:33
0
1
435

I am developing an application based on nextJS and integrating stripe's web elements (cards), but these elements are not displayed. I saw on inspection that it was empty. They work fine in my other reactJS apps, but not here, even though the code is the same. What did i do wrong?

import { Elements } from "@stripe/react-stripe-js";
import { loadStripe } from "@stripe/stripe-js";

async function loadStripePromise(){
    const stripePromise = await loadStripe('PUBLISHABLE_KEY');
    return stripePromise;
}

const AddStripeCreditCard: React.FC<AddStripeCreditCardProps> = ({
  show,
  close,
}) => {
  return (
    <CustomModal show={show} close={close} >
      <Elements stripe={loadStripePromise()}>
        <CardDetailsForm />
      </Elements>
    </CustomModal>
  );
};
import { useElements, useStripe } from '@stripe/react-stripe-js';
import {
    CardNumberElement,
    CardCvcElement,
    CardExpiryElement,
    CardElement
  } from "@stripe/react-stripe-js";
  
const CardDetailsForm = () => {
  
  return (
    <form onSubmit={handleSubmit}>
        
      <label>
        卡号
        <CardNumberElement
          options={options}
          id='cardNumber'
        />
      </label>
      <label>
        有效期
        <CardExpiryElement
          options={options}
        />
      </label>
      <label>
        CVC
        <CardCvcElement
          options={options}
        />
      </label>
      <button type="submit" disabled={!stripe}>
        支付
      </button>
    </form>
  );
};

The card element is not displayed, I also tried cardElement.

P粉458913655
P粉458913655

reply all(1)
P粉633075725

The problem is most likely related to you initializing stripePromise asynchronously by calling loadStripe by calling async function loadStripePromise()

I think loadStripe needs to be run synchronously to initialize the elements correctly. There is an example in the documentation here

const stripePromise = loadStripe(...)

...

return (
    
      
    
  );
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!