React Stripe.js reference (2024)

Learn about React components for Stripe.js and Stripe Elements.

React Stripe.js is a thin wrapper around Stripe Elements. It allows you to add Elements to any React app.

The Stripe.js reference covers complete Elements customization details.

You can use Elements with any Stripe product to collect online payments. To find the right integration path for your business, explore our docs.

Note

This reference covers the full React Stripe.js API. If you prefer to learn by doing, check out our documentation on accepting a payment or take a look at a sample integration.

Before you beginReact Stripe.js reference (1)

This doc assumes that you already have a basic working knowledge of React and that you have already set up a React project. If you’re new to React, we recommend that you take a look at the Getting Started guide before continuing.

SetupReact Stripe.js reference (2)

Install React Stripe.js and the Stripe.js loader from the npm public registry.

Command Line

npm install --save @stripe/react-stripe-js @stripe/stripe-js

Elements providerReact Stripe.js reference (3)

The Elements provider allows you to use Element components and access the Stripe object in any nested component. Render an Elements provider at the root of your React app so that it is available everywhere you need it.

To use the Elements provider, call loadStripe from @stripe/stripe-js with your publishable key. The loadStripe function asynchronously loads the Stripe.js script and initializes a Stripe object. Pass the returned Promise to Elements.

index.js

import {Elements} from '@stripe/react-stripe-js';import {loadStripe} from '@stripe/stripe-js';// Make sure to call `loadStripe` outside of a component’s render to avoid// recreating the `Stripe` object on every render.const stripePromise = loadStripe(

'pk_test_TYooMQauvdEDq54NiTphI7jx'

);export default function App() { const options = { // passing the client secret obtained from the server clientSecret: '{{CLIENT_SECRET}}', }; return ( <Elements stripe={stripePromise} options={options}> <CheckoutForm /> </Elements> );};

propdescription

stripe

required Stripe | null | Promise<Stripe | null>

A Stripe object or a Promise resolving to a Stripe object. The easiest way to initialize a Stripe object is with the Stripe.js wrapper module. After you set this prop, you can’t change it.

You can also pass in null or a Promise resolving to null if you’re performing an initial server-side render or when generating a static site.

options

optional Object

Optional Elements configuration options. See available options. To create Payment Elements, you must include the Intent’s clientSecret unless you render the element before creating the Intent.

Because props are immutable, you can’t change options after setting it. However, you can change the appearance of an element by calling the elements.update method.

Element componentsReact Stripe.js reference (4)

Element components provide a flexible way to securely collect payment information in your React app.

You can mount individual Element components inside of your Elements tree. Note that you can only mount one of each type of Element in a single <Elements> group.

CheckoutForm.js

import {PaymentElement} from '@stripe/react-stripe-js';const CheckoutForm = () => { return ( <form> <PaymentElement /> <button>Submit</button> </form> );};export default CheckoutForm;

prop description

id

optional string

Passes through to the Element’s container.

className

optional string

Passes through to the Element’s container.

options

optional Object

An object containing Element configuration options. See available options for the Payment Element or available options for individual payment method Elements.

onBlur

optional () => void

Triggered when the Element loses focus.

onChange

optional (event: Object) => void

Triggered when data exposed by this Element is changed (for example, when there is an error).

For more information, refer to the Stripe.js reference.

onClick

optional (event: Object) => void

Triggered by the <PaymentRequestButtonElement> when it is clicked.

For more information, refer to the Stripe.js reference.

onEscape

optional (event: Object) => void

Triggered when the escape key is pressed within an Element.

For more information, refer to the Stripe.js reference.

onFocus

optional () => void

Triggered when the Element receives focus.

onLoaderror

optional (event: Object) => void

Triggered when the Element fails to load.

This event is only emitted from the payment, linkAuthentication, address, and expressCheckout Elements.

For more information, refer to the Stripe.js reference.

onLoaderStart

optional (event: Object) => void

Triggered when the loader UI is mounted to the DOM and ready to be displayed.

This event is only emitted from the payment, linkAuthentication, and address Elements.

For more information, refer to the Stripe.js reference.

onReady

optional (element: Element) => void

Triggered when the Element is fully rendered and can accept imperative element.focus() calls. Called with a reference to the underlying Element instance.

Available Element componentsReact Stripe.js reference (5)

There are many different kinds of Elements, useful for collecting different kinds of payment information. These are the available Elements today.

ComponentUsage
AddressElementCollects address details for 236+ regional formats. See the Address Element docs.
AfterpayClearpayMessageElementDisplays installments messaging for Afterpay payments.
AuBankAccountElementCollects Australian bank account information (BSB and account number) for use with BECS Direct Debit payments.
CardCvcElementCollects the card‘s CVC number.
CardElementA flexible single-line input that collects all necessary card details.
CardExpiryElementCollects the card‘s expiration date.
CardNumberElementCollects the card number.
ExpressCheckoutElementAllows you to accept card or wallet payments through one or more payment buttons, including Apple Pay, Google Pay, Link, or PayPal. See the Express Checkout Element docs.
FpxBankElementThe customer’s bank, for use with FPX payments.
IbanElementThe International Bank Account Number (IBAN). Available for SEPA countries.
IdealBankElementThe customer’s bank, for use with iDEAL payments.
LinkAuthenticationElementCollects email addresses and allows users to log in to Link. See the Link Authentication Element docs.
PaymentElementCollects payment details for 25+ payment methods from around the globe. See the Payment Element docs.
PaymentRequestButtonElementAn all-in-one checkout button backed by either Apple Pay or the Payment Request API. See the Payment Request Button docs.

useElements hookReact Stripe.js reference (6)

useElements(): Elements | null

To safely pass the payment information collected by the Payment Element to the Stripe API, access the Elements instance so that you can use it with stripe.confirmPayment. If you use the React Hooks API, then useElements is the recommended way to access a mounted Element. If you need to access an Element from a class component, use ElementsConsumer instead.

Note

Note that if you pass a Promise to the Elements provider and the Promise hasn’t yet resolved, then useElements will return null.

CheckoutForm.js

import {useStripe, useElements, PaymentElement} from '@stripe/react-stripe-js';const CheckoutForm = () => { const stripe = useStripe(); const elements = useElements(); const handleSubmit = async (event) => { // We don't want to let default form submission happen here, // which would refresh the page. event.preventDefault(); if (!stripe || !elements) { // Stripe.js hasn't yet loaded. // Make sure to disable form submission until Stripe.js has loaded. return; } const result = await stripe.confirmPayment({ //`Elements` instance that was used to create the Payment Element elements, confirmParams: { return_url: "https://example.com/order/123/complete", }, }); if (result.error) { // Show error to your customer (for example, payment details incomplete) console.log(result.error.message); } else { // Your customer will be redirected to your `return_url`. For some payment // methods like iDEAL, your customer will be redirected to an intermediate // site first to authorize the payment, then redirected to the `return_url`. } }; return ( <form onSubmit={handleSubmit}> <PaymentElement /> <button disabled={!stripe}>Submit</button> </form> )};export default CheckoutForm;

useStripe hookReact Stripe.js reference (7)

useStripe(): Stripe | null

The useStripe hook returns a reference to the Stripe instance passed to the Elements provider. If you need to access the Stripe object from a class component, use ElementsConsumer instead.

Note

Note that if you pass a Promise to the Elements provider and the Promise hasn’t yet resolved, then useStripe will return null.

CheckoutForm.js

import {useStripe, useElements, PaymentElement} from '@stripe/react-stripe-js';const CheckoutForm = () => { const stripe = useStripe(); const elements = useElements(); const handleSubmit = async (event) => { // We don't want to let default form submission happen here, // which would refresh the page. event.preventDefault(); if (!stripe || !elements) { // Stripe.js hasn't yet loaded. // Make sure to disable form submission until Stripe.js has loaded. return; } const result = await stripe.confirmPayment({ //`Elements` instance that was used to create the Payment Element elements, confirmParams: { return_url: "https://example.com/order/123/complete", }, }); if (result.error) { // Show error to your customer (for example, payment details incomplete) console.log(result.error.message); } else { // Your customer will be redirected to your `return_url`. For some payment // methods like iDEAL, your customer will be redirected to an intermediate // site first to authorize the payment, then redirected to the `return_url`. } }; return ( <form onSubmit={handleSubmit}> <PaymentElement /> <button disabled={!stripe}>Submit</button> </form> )};export default CheckoutForm;

ElementsConsumer React Stripe.js reference (8)

To safely pass the payment information collected by the Payment Element to the Stripe API, access the Elements instance so that you can use it with stripe.confirmPayment. If you need to access the Stripe object or an Element from a class component, then ElementsConsumer provides an alternative to the useElements and useStripe hooks.

CheckoutForm.js

import {ElementsConsumer, PaymentElement} from '@stripe/react-stripe-js';class CheckoutForm extends React.Component { handleSubmit = async (event) => { // We don't want to let default form submission happen here, // which would refresh the page. event.preventDefault(); const {stripe, elements} = this.props; if (!stripe || !elements) { // Stripe.js hasn't yet loaded. // Make sure to disable form submission until Stripe.js has loaded. return; } const result = await stripe.confirmPayment({ //`Elements` instance that was used to create the Payment Element elements, confirmParams: { return_url: "https://example.com/order/123/complete", }, }); if (result.error) { // Show error to your customer (for example, payment details incomplete) console.log(result.error.message); } else { // Your customer will be redirected to your `return_url`. For some payment // methods like iDEAL, your customer will be redirected to an intermediate // site first to authorize the payment, then redirected to the `return_url`. } }; render() { return ( <form onSubmit={this.handleSubmit}> <PaymentElement /> <button disabled={!this.props.stripe}>Submit</button> </form> ); }}export default function InjectedCheckoutForm() { return ( <ElementsConsumer> {({stripe, elements}) => ( <CheckoutForm stripe={stripe} elements={elements} /> )} </ElementsConsumer> )}

prop description

children

required ({elements, stripe}) => ReactNode

This component takes a function as child. The function that you provide will be called with the Elements object that is managing your Element components and the Stripe object that you passed to <Elements>.

Note that if you pass a Promise to the Elements provider and the Promise hasn’t yet resolved, then stripe and elements will be null.

Customization and stylingReact Stripe.js reference (9)

Each element is mounted in an iframe, which means that Elements probably won’t work with any existing styling and component frameworks that you have. Despite this, you can still configure Elements to match the design of your site. Customizing Elements consists of responding to events and configuring Elements with the appearance option. The layout of each Element stays consistent, but you can modify colors, fonts, borders, padding, and more.

Customer location

Size

Theme

Layout

This demo only displays Google Pay or Apple Pay if you have an active card with either wallet.

Next stepsReact Stripe.js reference (10)

Build an integration with React Stripe.js and Elements.

  • Accept a payment
  • Accept a payment with the Express Checkout Element
  • Adding the Payment Request Button
  • Learn about the Elements Appearance API
  • Stripe.js reference
React Stripe.js reference (2024)

References

Top Articles
Small Thanksgiving Dinner Recipes - My Gorgeous Recipes
Chocolate Turtle Pecan Cluster Recipe
Moon Stone Pokemon Heart Gold
Craigslist Monterrey Ca
Botw Royal Guard
Mountain Dew Bennington Pontoon
Ret Paladin Phase 2 Bis Wotlk
Lifebridge Healthstream
Beacon Schnider
Fusion
Hay day: Top 6 tips, tricks, and cheats to save cash and grow your farm fast!
Shaniki Hernandez Cam
What is IXL and How Does it Work?
Garrick Joker'' Hastings Sentenced
Local Dog Boarding Kennels Near Me
10 Free Employee Handbook Templates in Word & ClickUp
Hijab Hookup Trendy
Baywatch 2017 123Movies
Cashtapp Atm Near Me
Craftology East Peoria Il
Khiara Keating: Manchester City and England goalkeeper convinced WSL silverware is on the horizon
All Obituaries | Buie's Funeral Home | Raeford NC funeral home and cremation
Jbf Wichita Falls
Teacup Yorkie For Sale Up To $400 In South Carolina
Best Nail Salons Open Near Me
SN100C, An Australia Trademark of Nihon Superior Co., Ltd.. Application Number: 2480607 :: Trademark Elite Trademarks
Anotherdeadfairy
6892697335
Masterbuilt Gravity Fan Not Working
Stockton (California) – Travel guide at Wikivoyage
Hwy 57 Nursery Michie Tn
950 Sqft 2 BHK Villa for sale in Devi Redhills Sirinium | Red Hills, Chennai | Property ID - 15334774
Does Royal Honey Work For Erectile Dysfunction - SCOBES-AR
031515 828
FREE Houses! All You Have to Do Is Move Them. - CIRCA Old Houses
The Ultimate Guide to Obtaining Bark in Conan Exiles: Tips and Tricks for the Best Results
Newcardapply Com 21961
Joplin Pets Craigslist
Solemn Behavior Antonym
Blasphemous Painting Puzzle
Craiglist Hollywood
Spectrum Outage in Genoa City, Wisconsin
Rush Copley Swim Lessons
Mitchell Kronish Obituary
9:00 A.m. Cdt
Port Huron Newspaper
Treatise On Jewelcrafting
Black Adam Showtimes Near Kerasotes Showplace 14
Razor Edge Gotti Pitbull Price
The Significance Of The Haitian Revolution Was That It Weegy
Cataz.net Android Movies Apk
Latest Posts
Article information

Author: Rubie Ullrich

Last Updated:

Views: 6212

Rating: 4.1 / 5 (52 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Rubie Ullrich

Birthday: 1998-02-02

Address: 743 Stoltenberg Center, Genovevaville, NJ 59925-3119

Phone: +2202978377583

Job: Administration Engineer

Hobby: Surfing, Sailing, Listening to music, Web surfing, Kitesurfing, Geocaching, Backpacking

Introduction: My name is Rubie Ullrich, I am a enthusiastic, perfect, tender, vivacious, talented, famous, delightful person who loves writing and wants to share my knowledge and understanding with you.