React React integration of Payment Intents API & Stripe Elements

This lesson is available for PRO members or as a single course purchase. Sign-in and choose a plan below.


*Enrollment provides full access to this course (and updates) for life.

Or Signup for Unlimited PRO Access

React Payments UI

Payments.js
import React, { useState } from 'react';
import { fetchFromAPI } from './helpers';
import { CardElement, useStripe, useElements } from '@stripe/react-stripe-js';

function Payments() {
  const stripe = useStripe();
  const elements = useElements();

  const [amount, setAmount] = useState(0);
  const [paymentIntent, setPaymentIntent] = useState();

  // Create a payment intent on the server
  const createPaymentIntent = async (event) => {

    // Clamp amount to Stripe min/max
    const validAmonut = Math.min(Math.max(amount, 50), 9999999);
    setAmount(validAmonut);

    // Make the API Request
    const pi = await fetchFromAPI('payments', { body: { amount: validAmonut } });
    setPaymentIntent(pi);
  };

  // Handle the submission of card details
  const handleSubmit = async (event) => {
    event.preventDefault();

    const cardElement = elements.getElement(CardElement);

    // Confirm Card Payment
    const {
      paymentIntent: updatedPaymentIntent,
      error,
    } = await stripe.confirmCardPayment(paymentIntent.client_secret, {
      payment_method: { card: cardElement },
    });

    if (error) {
      console.error(error);
      error.payment_intent && setPaymentIntent(error.payment_intent);
    } else {
      setPaymentIntent(updatedPaymentIntent);
    }
  };

  return (
    <>

      <div>
        <input
          type="number"
          value={amount}
          disabled={paymentIntent}
          onChange={(e) => setAmount(e.target.value)}
        />
        <button
          disabled={amount <= 0}
          onClick={createPaymentIntent}
          hidden={paymentIntent}>
          Ready to Pay ${ (amount / 100).toFixed(2) }
        </button>
      </div>


      <form onSubmit={handleSubmit}>


        <CardElement />
        <button  type="submit">
          Pay
        </button>
      </form>
    </>
  );
}

Q&A Chat