search

Home  >  Q&A  >  body text

Stripe Elements in NextJS app not showing

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粉458913655P粉458913655433 days ago664

reply all(1)I'll reply

  • P粉633075725

    P粉6330757252023-09-17 21:45:09

    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 (
        <Elements stripe={stripePromise} options={options}>
          <CheckoutForm />
        </Elements>
      );

    reply
    0
  • Cancelreply