### Checkout Form Provider Example
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/configuration.md
Example of how to use the CheckoutFormProvider with specific options including clientSecret, appearance, and loader settings. Used by CheckoutFormProvider.
```typescript
import {CheckoutFormProvider} from '@stripe/react-stripe-js/checkout';
import React from 'react';
export const Checkout = () => {
const options = {
clientSecret: 'pi_test_secret',
appearance: {
theme: 'stripe',
variables: {colorPrimary: '#0570de'},
},
loader: 'auto',
};
return (
{/* Components */}
);
};
```
--------------------------------
### CheckoutElementsProvider Usage Example
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/api-reference/checkout-providers.md
This example shows how to set up the CheckoutElementsProvider with a Stripe instance and client secret, and how to use the useCheckoutElements hook to render a PaymentElement and handle form submission.
```typescript
import React from 'react';
import {loadStripe} from '@stripe/stripe-js';
import {
CheckoutElementsProvider,
PaymentElement,
useCheckoutElements,
} from '@stripe/react-stripe-js/checkout';
const stripePromise = loadStripe('pk_test_YOUR_KEY');
const CheckoutForm = () => {
const {type, checkout, error} = useCheckoutElements();
if (type === 'loading') {
return
Loading...
;
}
if (type === 'error') {
return
Error: {error.message}
;
}
const handleSubmit = async () => {
const {error: submitError} = await checkout.submit();
if (submitError) {
console.error(submitError);
}
};
return (
<>
>
);
};
const CheckoutPage = () => {
const [clientSecret, setClientSecret] = React.useState('');
React.useEffect(() => {
fetch('/create-payment-intent', {method: 'POST'})
.then((res) => res.json())
.then((data) => setClientSecret(data.clientSecret));
}, []);
return (
);
};
```
--------------------------------
### Payment Request Button Usage Example
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/api-reference/element-components.md
Example of how to use the PaymentRequestButtonElement to create a payment request button. Ensure you have initialized Stripe and Elements before mounting.
```javascript
import {PaymentRequestButtonElement, useElements, useStripe} from '@stripe/react-stripe-js';
import React from 'react';
const PaymentButton = () => {
const stripe = useStripe();
const elements = useElements();
const handleClick = async (event) => {
if (!stripe) return;
const paymentRequest = stripe.paymentRequest({
country: 'US',
currency: 'usd',
total: {label: 'Total', amount: 1099},
requestPayerName: true,
requestPayerEmail: true,
});
const prButton = elements.create('paymentRequestButton', {paymentRequest});
prButton.mount('#payment-request-button');
};
return ;
};
```
--------------------------------
### Checkout Elements Provider Usage Example
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/configuration.md
Demonstrates how to use the `CheckoutElementsProvider` with dynamic appearance options. The `clientSecret` and `elementsOptions.appearance` can be updated as needed.
```typescript
import {CheckoutElementsProvider} from '@stripe/react-stripe-js/checkout';
import React from 'react';
export const Checkout = () => {
const [appearance, setAppearance] = React.useState({
theme: 'stripe',
});
const options = {
clientSecret: 'pi_test_secret',
elementsOptions: {appearance},
};
return (
{/* Components */}
);
};
```
--------------------------------
### Install Stripe dependencies
Source: https://github.com/stripe/react-stripe-js/blob/master/README.md
Install the necessary Stripe packages via npm to begin integrating payment functionality into your React project.
```shell
npm install @stripe/react-stripe-js @stripe/stripe-js
```
--------------------------------
### Example Appearance Configuration - React Stripe.js
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/configuration.md
Demonstrates how to apply custom themes, variables, and CSS rules to Stripe Elements. Use this to match your brand's visual identity.
```typescript
const options = {
clientSecret: 'pi_test_secret',
elementsOptions: {
appearance: {
theme: 'stripe',
variables: {
colorPrimary: '#0070f3',
colorBackground: '#ffffff',
colorText: '#30313d',
colorDanger: '#df1b41',
borderRadius: '4px',
fontFamily: 'Sohne, system-ui, sans-serif',
fontSizeBase: '16px',
},
rules: {
'.Element': {
padding: '10px',
border: '1px solid #e0e0e0',
},
'.Element:focus': {
borderColor: '#0070f3',
},
},
},
},
};
```
--------------------------------
### Elements Provider Setup
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/api-reference/elements-provider.md
Use the `Elements` provider to make Stripe.js and Elements available to your checkout form. Pass a Promise returned by `loadStripe` to the `stripe` prop. This example demonstrates a typical checkout flow including payment element and confirmation.
```typescript
import React from 'react';
import {loadStripe} from '@stripe/stripe-js';
import {Elements, PaymentElement, useStripe, useElements} from '@stripe/react-stripe-js';
const stripePromise = loadStripe('pk_test_YOUR_PUBLISHABLE_KEY');
const CheckoutForm = () => {
const stripe = useStripe();
const elements = useElements();
const [error, setError] = React.useState(null);
const handleSubmit = async (e) => {
e.preventDefault();
if (!elements || !stripe) return;
const {error: submitError} = await elements.submit();
if (submitError) {
setError(submitError.message);
return;
}
const res = await fetch('/create-payment-intent', {method: 'POST'});
const {clientSecret} = await res.json();
const {error: confirmError} = await stripe.confirmPayment({
elements,
clientSecret,
confirmParams: {return_url: 'https://example.com/success'},
});
if (confirmError) {
setError(confirmError.message);
}
};
return (
);
};
export default function App() {
return (
);
}
```
--------------------------------
### BillingAddressElement Usage Example
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/api-reference/checkout-elements.md
Demonstrates how to integrate the BillingAddressElement into a React component to collect billing addresses. Includes an example of handling address changes.
```typescript
import {BillingAddressElement, useCheckoutElements} from '@stripe/react-stripe-js/checkout';
const BillingForm = () => {
const {checkout} = useCheckoutElements();
const handleChange = (event) => {
console.log('Billing address:', event.value?.address);
};
return (
);
};
```
--------------------------------
### Install React Stripe.js dependencies
Source: https://github.com/stripe/react-stripe-js/blob/master/docs/migrating.md
Commands to remove the legacy library and install the required Stripe packages via npm.
```shell
npm uninstall react-stripe-elements
npm install @stripe/react-stripe-js @stripe/stripe-js
```
--------------------------------
### EmbeddedCheckoutProvider Usage Example
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/api-reference/embedded-checkout.md
This example demonstrates how to set up the EmbeddedCheckoutProvider with a Stripe object, a client secret fetched from an API, and callbacks for shipping details changes and completion. It uses React's useState and useEffect hooks for managing state and side effects.
```typescript
import React from 'react';
import {loadStripe} from '@stripe/stripe-js';
import {
EmbeddedCheckoutProvider,
EmbeddedCheckout,
} from '@stripe/react-stripe-js';
const stripePromise = loadStripe('pk_test_YOUR_PUBLISHABLE_KEY');
export const CheckoutPage = () => {
const [clientSecret, setClientSecret] = React.useState(null);
const handleShippingChange = async (event) => {
// Call your backend to update shipping costs and line items
const response = await fetch('/api/update-shipping', {
method: 'POST',
body: JSON.stringify({address: event.address}),
});
const result = await response.json();
if (result.success) {
return {result: 'success'};
} else {
return {result: 'error', error: {message: result.error}};
}
};
React.useEffect(() => {
fetch('/create-checkout-session', {method: 'POST'})
.then((res) => res.json())
.then((data) => setClientSecret(data.clientSecret));
}, []);
return (
console.log('Checkout complete'),
}}
>
);
};
```
--------------------------------
### Example Font Configuration - React Stripe.js
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/configuration.md
Shows how to load custom fonts like Roboto for use in Stripe Elements. This allows for consistent typography across your application.
```typescript
const options = {
clientSecret: 'pi_test_secret',
elementsOptions: {
fonts: [
{
cssSrc:
'https://fonts.googleapis.com/css?family=Roboto&display=optional',
family: 'Roboto',
weight: 400,
},
{
cssSrc:
'https://fonts.googleapis.com/css?family=Roboto:700&display=optional',
family: 'Roboto',
weight: 700,
},
],
},
};
```
--------------------------------
### IbanElement Usage Example
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/api-reference/element-components.md
Example of using the IbanElement for SEPA payments. This snippet demonstrates how to integrate the IbanElement into a form and use Stripe's `createSource` method to process SEPA debit information.
```typescript
import {IbanElement, useStripe, useElements} from '@stripe/react-stripe-js';
const SEPAForm = () => {
const stripe = useStripe();
const elements = useElements();
const handleSubmit = async (e) => {
e.preventDefault();
const {error, source} = await stripe.createSource({
type: 'sepa_debit',
currency: 'eur',
owner: {
name: 'Jenny Rosen',
email: 'jenny@example.com',
},
mandate: {
notification_method: 'email',
},
}, elements.getElement(IbanElement));
if (error) {
console.error(error);
}
};
return (
);
};
```
--------------------------------
### Server-Side Rendering Setup
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/README.md
For Server-Side Rendering (SSR), initialize the `Elements` provider with `stripe={null}` initially. After the component hydrates, use `useEffect` to load Stripe and update the `stripe` prop.
```typescript
// Pass null initially for SSR
// After hydration, provide stripe
useEffect(() => {
setStripe(loadStripe('pk_test_YOUR_KEY'));
}, []);
```
--------------------------------
### CheckoutForm Usage Example
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/api-reference/checkout-elements.md
Demonstrates how to use the CheckoutForm component within a React application. It includes setting up event handlers for payment confirmation and cancellation, and displaying form status and total amount.
```typescript
import React from 'react';
import {CheckoutForm, useCheckoutForm} from '@stripe/react-stripe-js/checkout';
const FormCheckoutComponent = () => {
const {type, checkout} = useCheckoutForm();
const [isSubmitting, setIsSubmitting] = React.useState(false);
const handleConfirm = async (event) => {
setIsSubmitting(true);
// Handle payment confirmation
};
const handleCancel = () => {
console.log('Buyer dismissed payment interface');
};
if (type === 'loading') {
return
>
);
};
```
--------------------------------
### Basic ShippingAddressElement Usage
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/api-reference/checkout-elements.md
Demonstrates how to integrate the ShippingAddressElement into a React component. It includes an example of handling address changes via the onChange callback.
```typescript
import {ShippingAddressElement} from '@stripe/react-stripe-js/checkout';
const ShippingForm = () => {
const handleChange = (event) => {
if (event.value) {
console.log('Shipping address:', event.value.address);
}
};
return (
);
};
```
--------------------------------
### PaymentElement Usage Example
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/api-reference/element-components.md
Demonstrates how to use the PaymentElement for collecting payment details. It includes handling available payment methods and submitting payment information. Ensure you have initialized Stripe and Elements providers before using this component.
```typescript
import {PaymentElement, useElements, useStripe} from '@stripe/react-stripe-js';
import React from 'react';
const CheckoutForm = () => {
const stripe = useStripe();
const elements = useElements();
const [error, setError] = React.useState(null);
const [paymentMethods, setPaymentMethods] = React.useState([]);
const handleAvailableMethodsChange = (event) => {
setPaymentMethods(event.availablePaymentMethods);
};
const handleSubmit = async (e) => {
e.preventDefault();
if (!elements || !stripe) return;
const {error: submitError} = await elements.submit();
if (submitError) {
setError(submitError.message);
return;
}
const res = await fetch('/create-intent', {method: 'POST'});
const {clientSecret} = await res.json();
const {error: confirmError} = await stripe.confirmPayment({
elements,
clientSecret,
confirmParams: {return_url: 'https://example.com/success'},
});
if (confirmError) {
setError(confirmError.message);
}
};
return (
);
};
```
--------------------------------
### Use useCheckoutForm Hook
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/api-reference/hooks.md
This example demonstrates how to use the useCheckoutForm hook to conditionally render UI based on the checkout SDK's loading, success, or error state. It includes logic for submitting payment using the checkout object.
```typescript
import React from 'react';
import {useCheckoutForm} from '@stripe/react-stripe-js/checkout';
const CheckoutForm = () => {
const checkoutResult = useCheckoutForm();
if (checkoutResult.type === 'loading') {
return
>
);
};
```
--------------------------------
### AddressElement Usage Example
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/api-reference/element-components.md
Demonstrates how to integrate and use the AddressElement component in a React form for collecting billing addresses. It includes handling changes and submitting the collected address.
```typescript
import {AddressElement, useElements} from '@stripe/react-stripe-js';
import React from 'react';
const AddressForm = () => {
const elements = useElements();
const [address, setAddress] = React.useState(null);
const handleChange = (event) => {
setAddress(event.value);
};
const handleSubmit = async () => {
const {error, value} = await elements.submit();
if (!error) {
console.log('Address:', value.address);
}
};
return (
<>
>
);
};
```
--------------------------------
### Import Main Module Exports
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/INDEX.md
Import common components, hooks, and providers from the main module of React Stripe.js. Ensure you have the library installed.
```typescript
// Providers
import {Elements, EmbeddedCheckout, EmbeddedCheckoutProvider} from '@stripe/react-stripe-js'
// Hooks
import {useStripe, useElements} from '@stripe/react-stripe-js'
// Elements (24+ components)
import {PaymentElement, CardElement, AddressElement, ...} from '@stripe/react-stripe-js'
// Disclosure
import {FinancialAccountDisclosure, IssuingDisclosure} from '@stripe/react-stripe-js'
```
--------------------------------
### Render EmbeddedCheckout Component
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/api-reference/embedded-checkout.md
Use the EmbeddedCheckout component inside an EmbeddedCheckoutProvider. Ensure the provider is configured with a Stripe instance and a fetchClientSecret function. This example shows basic setup with a div wrapper.
```typescript
import React from 'react';
import {
EmbeddedCheckoutProvider,
EmbeddedCheckout,
} from '@stripe/react-stripe-js';
import {loadStripe} from '@stripe/stripe-js';
const stripePromise = loadStripe('pk_test_YOUR_KEY');
export const CheckoutPage = () => {
const fetchClientSecret = async () => {
const response = await fetch('/create-intent', {method: 'POST'});
const {clientSecret} = await response.json();
return clientSecret;
};
return (
);
};
```
--------------------------------
### Fix useCheckout/useCheckoutElements in Both Providers
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/errors.md
Avoid nesting components that use checkout hooks within both an `` provider and a checkout provider (`CheckoutElementsProvider` or `CheckoutFormProvider`). The example shows the incorrect dual nesting and the correct approach of using only one provider.
```typescript
// ✗ Wrong - don't nest both
{/* ERROR - can't use both providers */}
// ✓ Correct - use one or the other
// OR
```
--------------------------------
### CardElement Usage Example
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/api-reference/element-components.md
Use CardElement for a complete, all-in-one card payment form. It handles input for card number, expiry, and CVC. The onChange handler can be used to display errors.
```typescript
import {CardElement, useElements, useStripe} from '@stripe/react-stripe-js';
const CardForm = () => {
const stripe = useStripe();
const elements = useElements();
const handleChange = (event) => {
if (event.error) {
console.log(event.error.message);
}
};
const handleSubmit = async (e) => {
e.preventDefault();
const {error, paymentMethod} = await stripe.createPaymentMethod({
type: 'card',
card: elements.getElement(CardElement),
});
if (error) {
console.error(error);
} else {
console.log('Payment method:', paymentMethod);
}
};
return (
);
};
```
--------------------------------
### Initialize CheckoutFormProvider
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/api-reference/checkout-providers.md
Wrap your checkout form with CheckoutFormProvider, passing the Stripe instance and SDK options. The clientSecret is typically fetched from your server. Ensure the Stripe instance is loaded before rendering the provider.
```typescript
import React from 'react';
import {loadStripe} from '@stripe/stripe-js';
import {
CheckoutFormProvider,
CheckoutForm,
useCheckoutForm,
} from '@stripe/react-stripe-js/checkout';
const stripePromise = loadStripe('pk_test_YOUR_KEY');
const CheckoutPage = () => {
const [clientSecret, setClientSecret] = React.useState('');
React.useEffect(() => {
fetch('/create-payment-intent', {method: 'POST'})
.then((res) => res.json())
.then((data) => setClientSecret(data.clientSecret));
}, []);
const handleFormSubmit = async () => {
// Form submission handled by CheckoutForm component
};
return (
Checkout
);
};
```
--------------------------------
### Server-Side Rendering Configuration
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/configuration.md
For SSR, initialize the Elements component with `null` for the stripe prop. Hydrate with the Stripe instance after the component mounts on the client.
```typescript
// For SSR, pass null initially
{/* Components render empty on server */}
// After hydration, provide the Stripe instance
useEffect(() => {
setStripeInstance(loadStripe('pk_test_YOUR_KEY'));
}, []);
```
--------------------------------
### Get Specific Element Instance
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/README.md
Import `CardElement` and `useElements` to retrieve a specific element instance, such as the `CardElement`, from the Elements instance. This allows for direct interaction with the element.
```typescript
import {CardElement, useElements} from '@stripe/react-stripe-js';
function Form() {
const elements = useElements();
const cardElement = elements.getElement(CardElement);
}
```
--------------------------------
### Access Stripe Instance with useStripe
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/README.md
Use the `useStripe` hook to get access to the Stripe object. This object is required for creating payment methods and other Stripe operations.
```typescript
const stripe = useStripe();
const paymentMethod = await stripe.createPaymentMethod({...});
```
--------------------------------
### Access Elements with useElements
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/README.md
Use the `useElements` hook to get access to the Elements instance. This is necessary for retrieving specific Elements like the CardElement and submitting form data.
```typescript
const elements = useElements();
const cardElement = elements.getElement(CardElement);
const {error} = await elements.submit();
```
--------------------------------
### Initialize Stripe and Elements provider
Source: https://github.com/stripe/react-stripe-js/blob/master/docs/migrating.md
Replacing the legacy StripeProvider with the loadStripe helper and the Elements wrapper component.
```jsx
// Before
import {StripeProvider, Elements} from 'react-stripe-elements';
const App = () => (
{/* Your checkout form */}
);
// After
import {loadStripe} from '@stripe/stripe-js';
import {Elements} from '@stripe/react-stripe-js';
const stripePromise = loadStripe('pk_test_6pRNASCoBOKtIshFeQd4XMUh');
const App = () => (
{/* Your checkout form */}
);
```
--------------------------------
### useCheckout (Deprecated)
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/api-reference/hooks.md
Deprecated hook for backward compatibility. Use `useCheckoutElements()` or `useCheckoutForm()` instead.
```APIDOC
## useCheckout (Deprecated)
Deprecated hook for backward compatibility. Use `useCheckoutElements()` or `useCheckoutForm()` instead.
**Module:** `@stripe/react-stripe-js/checkout`
### Signature
```typescript
export const useCheckout = (): StripeUseCheckoutResult
type StripeUseCheckoutResult =
| {type: 'loading'}
| {type: 'success'; checkout: StripeCheckoutValue}
| {type: 'error'; error: {message: string}}
```
### Deprecation Notice
Since v6.3.0. Will be removed in v7.0.0. Use provider-specific hooks:
- In ``: use `useCheckoutElements()`
- In ``: use `useCheckoutForm()`
The hook always returns the Elements-shaped result for backward compatibility, regardless of which provider wraps the tree.
### Source
`src/checkout/components/CheckoutContext.tsx`
```
--------------------------------
### CurrencySelectorElement Component (Beta)
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/api-reference/element-components.md
Beta component that allows customers to select their preferred payment currency. Requires beta access.
```typescript
export const CurrencySelectorElement: CurrencySelectorElementComponent
```
--------------------------------
### Fix useCheckoutElements in Wrong Provider
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/errors.md
Use `useCheckoutElements()` only within ``. Calling it inside `` is incorrect; use `useCheckoutForm()` instead. The example demonstrates the correct and incorrect provider nesting.
```typescript
// ✗ Wrong
// useCheckoutElements() ERROR
// ✓ Correct
// useCheckoutElements() OK
// ✓ Also correct for forms
// useCheckoutForm() OK
```
--------------------------------
### Get Element Instance with React Component Type
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/exports.md
Use `elements.getElement()` with React component types to retrieve specific element instances. This leverages the augmented `StripeElements` interface for type safety.
```typescript
const cardElement = elements.getElement(CardElement);
const paymentElement = elements.getElement(PaymentElement);
```
--------------------------------
### Correctly Initialize Stripe with Elements
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/errors.md
Ensure the `stripe` prop passed to `Elements` is a valid Stripe instance or a Promise resolving to one. Use `loadStripe` for correct initialization. `null` is acceptable for Server-Side Rendering.
```typescript
import {loadStripe} from '@stripe/stripe-js';
import {Elements} from '@stripe/react-stripe-js';
// ✓ Correct usage
const stripePromise = loadStripe('pk_test_YOUR_KEY');
...
// ✗ Wrong - passing plain object
...
// ✓ Also valid - null for SSR
...
```
--------------------------------
### Provider Components
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/exports.md
These components are essential for setting up the context required for checkout functionality. They manage the state and provide necessary data to child components and hooks.
```APIDOC
## Provider Components
### `CheckoutElementsProvider`
#### Description
Provides the necessary context for checkout elements and hooks. It should be wrapped around your application or the part of your application that uses checkout features.
### `CheckoutFormProvider`
#### Description
Provides the form context for checkout, managing form state and submission logic. Use this to enable form-related features within the checkout flow.
```
--------------------------------
### useCheckoutForm
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/api-reference/hooks.md
Hook to retrieve the Stripe Checkout Form SDK from a `CheckoutFormProvider` context. It returns the SDK in one of three states: loading, success, or error.
```APIDOC
## useCheckoutForm
Hook to retrieve the Stripe Checkout Form SDK from a `CheckoutFormProvider` context.
**Module:** `@stripe/react-stripe-js/checkout`
### Signature
```typescript
export const useCheckoutForm = (): StripeUseCheckoutFormResult
type StripeUseCheckoutFormResult =
| {type: 'loading'}
| {type: 'success'; checkout: StripeCheckoutFormValue}
| {type: 'error'; error: {message: string}}
type StripeCheckoutFormValue = StripeCheckoutFormActions & StripeCheckoutSession
```
### Returns
An object with one of three states:
- `{type: 'loading'}` - The checkout SDK is still initializing
- `{type: 'success'; checkout: StripeCheckoutFormValue}` - SDK ready with session and action methods
- `{type: 'error'; error: {message: string}}` - An error occurred during initialization
The `checkout` object includes methods from `StripeCheckoutFormSdk` and the session state.
### Usage Example
```typescript
import React from 'react';
import {useCheckoutForm} from '@stripe/react-stripe-js/checkout';
const CheckoutForm = () => {
const checkoutResult = useCheckoutForm();
if (checkoutResult.type === 'loading') {
return
>
);
};
```
### Error Conditions
- **Error when not in CheckoutFormProvider**: Throws if not inside a `CheckoutFormProvider`.
- **Error when in CheckoutElementsProvider**: Throws with message that `useCheckoutForm()` must be used inside `CheckoutFormProvider`, not `CheckoutElementsProvider`.
```
--------------------------------
### Fix useStripe Outside Provider
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/errors.md
Verify that `useStripe()` is invoked within either an `` or a checkout provider. The example contrasts a component calling `useStripe()` directly with one correctly nested inside an `` provider.
```typescript
// ✗ Wrong
function PaymentForm() {
const stripe = useStripe(); // ERROR
return ;
}
// ✓ Correct
function PaymentForm() {
const stripe = useStripe();
return ;
}
function App() {
return (
);
}
```
--------------------------------
### React Stripe.js Payment Form with Class Components
Source: https://github.com/stripe/react-stripe-js/blob/master/README.md
This snippet demonstrates how to create a payment form using React class components and React Stripe.js. It includes setting up the Elements context, handling form submission, and confirming the payment with Stripe. Dependencies include React, ReactDOM, and the @stripe/react-stripe-js library. It takes no explicit input but relies on the Stripe API for payment processing.
```jsx
import React from 'react';
import ReactDOM from 'react-dom';
import {loadStripe} from '@stripe/stripe-js';
import {
PaymentElement,
Elements,
ElementsConsumer,
} from '@stripe/react-stripe-js';
class CheckoutForm extends React.Component {
handleSubmit = async (event) => {
event.preventDefault();
const {stripe, elements} = this.props;
if (elements == null) {
return;
}
// Trigger form validation and wallet collection
const {error: submitError} = await elements.submit();
if (submitError) {
// Show error to your customer
return;
}
// Create the PaymentIntent and obtain clientSecret
const res = await fetch('/create-intent', {
method: 'POST',
});
const {client_secret: clientSecret} = await res.json();
const {error} = await stripe.confirmPayment({
//`Elements` instance that was used to create the Payment Element
elements,
clientSecret,
confirmParams: {
return_url: 'https://example.com/order/123/complete',
},
});
if (error) {
// This point will only be reached if there is an immediate error when
// confirming the payment. Show error to your customer (for example, payment
// details incomplete)
} 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() {
const {stripe} = this.props;
return (
);
}
}
const InjectedCheckoutForm = () => (
{({stripe, elements}) => (
)}
);
const stripePromise = loadStripe('pk_test_6pRNASCoBOKtIshFeQd4XMUh');
const options = {
mode: 'payment',
amount: 1099,
currency: 'usd',
// Fully customizable with appearance API.
appearance: {
/*...*/
},
};
const App = () => (
);
ReactDOM.render(, document.body);
```
--------------------------------
### Access Stripe Elements with useElements Hook
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/api-reference/elements-provider.md
Use the `useElements` hook within functional components to get the StripeElements instance. Ensure the component is wrapped in an `` provider. This instance is necessary for submitting payment details.
```typescript
import {useElements, PaymentElement} from '@stripe/react-stripe-js';
const CheckoutForm = () => {
const elements = useElements();
const handleSubmit = async () => {
if (!elements) return;
const {error} = await elements.submit();
if (error) {
console.error(error);
}
};
return (
<>
>
);
};
```
--------------------------------
### useStripe
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/api-reference/hooks.md
Hook to retrieve the Stripe instance from context. It returns the Stripe instance from the nearest `Elements` or checkout provider context, or `null` if not within a provider.
```APIDOC
## useStripe
### Description
Hook to retrieve the Stripe instance from context. Returns the Stripe instance from the nearest `Elements` or checkout provider context, or `null` if not within a provider.
### Signature
```typescript
export const useStripe = (): stripeJs.Stripe | null
```
### Returns
The Stripe instance from the nearest `Elements` or checkout provider context, or `null` if not within a provider.
### Usage Example
```typescript
import React from 'react';
import {useStripe} from '@stripe/react-stripe-js';
const PaymentForm = () => {
const stripe = useStripe();
const [status, setStatus] = React.useState(null);
const handlePayment = async () => {
if (!stripe) {
setStatus('Stripe not loaded');
return;
}
const result = await stripe.confirmCardPayment('pi_test_secret', {
payment_method: {card: {token: 'tok_visa'}},
});
if (result.error) {
setStatus(`Error: ${result.error.message}`);
} else {
setStatus('Payment succeeded');
}
};
return (
<>
{status &&
{status}
}
>
);
};
```
### Error Conditions
- **Error when not in provider**: Throws if called outside an `Elements`, `CheckoutElementsProvider`, or `CheckoutFormProvider` context.
```
--------------------------------
### Element Components
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/exports.md
These are pre-built UI components that simplify the integration of various checkout-related input fields.
```APIDOC
## Element Components
### `PaymentElement`
#### Description
A versatile element that can render various payment method inputs based on the checkout configuration.
### `CheckoutForm`
#### Description
A composite component that can render multiple checkout elements, often used for a complete checkout form.
### `ExpressCheckoutElement`
#### Description
An element designed to integrate with express checkout methods like Apple Pay or Google Pay.
### `CurrencySelectorElement`
#### Description
A component that allows users to select their desired currency.
### `TaxIdElement`
#### Description
An element for collecting tax identification numbers from the user.
### `ContactDetailsElement`
#### Description
A component for collecting user contact information.
### `BillingAddressElement`
#### Description
A component for collecting the user's billing address.
### `ShippingAddressElement`
#### Description
A component for collecting the user's shipping address.
```
--------------------------------
### Consumer Components
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/exports.md
Components that consume Stripe context.
```APIDOC
## ElementsConsumer
### Description
Component that consumes Stripe Elements context.
### Type
FunctionComponent
### Source
`src/components/Elements.tsx`
```
--------------------------------
### Access Stripe Instance with useStripe
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/api-reference/hooks.md
Use the `useStripe` hook to get the Stripe instance within your React component. Ensure the component is rendered within an `Elements` or checkout provider context. This hook returns the Stripe instance or null if not within a provider.
```typescript
import React from 'react';
import {useStripe} from '@stripe/react-stripe-js';
const PaymentForm = () => {
const stripe = useStripe();
const [status, setStatus] = React.useState(null);
const handlePayment = async () => {
if (!stripe) {
setStatus('Stripe not loaded');
return;
}
const result = await stripe.confirmCardPayment('pi_test_secret', {
payment_method: {card: {token: 'tok_visa'}},
});
if (result.error) {
setStatus(`Error: ${result.error.message}`);
} else {
setStatus('Payment succeeded');
}
};
return (
<>
{status &&
{status}
}
>
);
};
```
--------------------------------
### Update Elements Provider Client Secret
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/configuration.md
Example demonstrating how to update the clientSecret option for the Elements provider after initialization to handle new payment intents. This involves using React's useState hook to manage the client secret and passing it to the options prop.
```typescript
import React from 'react';
import {Elements} from '@stripe/react-stripe-js';
import {loadStripe} from '@stripe/stripe-js';
const stripePromise = loadStripe('pk_test_YOUR_KEY');
export const CheckoutPage = () => {
const [clientSecret, setClientSecret] = React.useState('pi_test_secret');
const options = {
clientSecret,
};
return (
{/* Components here */}
);
};
```
--------------------------------
### useCheckoutElements
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/api-reference/hooks.md
Hook to retrieve the Stripe Checkout Elements SDK from a `CheckoutElementsProvider` context. It returns an object with one of three states: loading, success, or error.
```APIDOC
## useCheckoutElements
### Description
Hook to retrieve the Stripe Checkout Elements SDK from a `CheckoutElementsProvider` context. Returns an object with one of three states: loading, success, or error.
### Signature
```typescript
export const useCheckoutElements = (): StripeUseCheckoutElementsResult
type StripeUseCheckoutElementsResult =
| {type: 'loading'}
| {type: 'success'; checkout: StripeCheckoutElementsValue}
| {type: 'error'; error: {message: string}}
type StripeCheckoutElementsValue = StripeCheckoutElementsActions & StripeCheckoutSession
```
### Returns
An object with one of three states:
- `{type: 'loading'}` - The checkout SDK is still initializing
- `{type: 'success'; checkout: StripeCheckoutElementsValue}` - SDK ready with session and action methods
- `{type: 'error'; error: {message: string}}` - An error occurred during initialization
The `checkout` object includes methods from `StripeCheckoutElementsSdk` (except `on` and `loadActions`) and the session state.
### Usage Example
```typescript
import React from 'react';
import {useCheckoutElements} from '@stripe/react-stripe-js/checkout';
const CheckoutComponent = () => {
const {type, checkout, error} = useCheckoutElements();
if (type === 'loading') {
return
Loading checkout...
;
}
if (type === 'error') {
return
Error: {error.message}
;
}
return (
Session amount: {checkout.amount_total}
);
};
```
### Error Conditions
- **Error when not in CheckoutElementsProvider**: Throws if not inside a `CheckoutElementsProvider`.
- **Error when in CheckoutFormProvider**: Throws with message that `useCheckoutElements()` must be used inside `CheckoutElementsProvider`, not `CheckoutFormProvider`.
```
--------------------------------
### Asynchronous Stripe Instance Configuration
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/configuration.md
Pass a Promise that resolves to a Stripe instance to the Elements component. This is the recommended approach for handling asynchronous loading.
```typescript
import {loadStripe} from '@stripe/stripe-js';
// loadStripe returns a Promise
const stripePromise = loadStripe('pk_test_YOUR_KEY');
// Pass the Promise directly
{/* Components */}
```
--------------------------------
### Core React Stripe.js Hooks and Providers
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/README.md
Illustrates the primary hooks and providers available in the main @stripe/react-stripe-js module for accessing Stripe and Elements instances.
```javascript
Elements (main)
├── useStripe() → Stripe instance
└── useElements() → StripeElements instance
```
--------------------------------
### Basic Payment Form with React Stripe.js
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/README.md
Implement a standard payment form using `Elements` and `PaymentElement`. Ensure Stripe and Elements are loaded before submitting the form. This pattern is suitable for custom payment UIs.
```typescript
import {loadStripe} from '@stripe/stripe-js';
import {Elements, PaymentElement, useStripe, useElements} from '@stripe/react-stripe-js';
const stripePromise = loadStripe('pk_test_YOUR_KEY');
function PaymentForm() {
const stripe = useStripe();
const elements = useElements();
const handleSubmit = async (e) => {
e.preventDefault();
if (!stripe || !elements) return;
const {error} = await elements.submit();
if (error) return;
const res = await fetch('/create-intent', {method: 'POST'});
const {clientSecret} = await res.json();
const result = await stripe.confirmPayment({
elements,
clientSecret,
confirmParams: {return_url: 'https://example.com/success'},
});
};
return (
);
}
export default function App() {
return (
);
}
```
--------------------------------
### Element Components
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/README.md
All available Element components for collecting payment details.
```APIDOC
## Payment Elements
### Description
Components for collecting various payment methods.
### Components
`PaymentElement`
`PaymentMethodMessagingElement`
## Card Elements
### Description
Components for collecting card details.
### Components
`CardElement`
(split card fields)
## Bank Account Elements
### Description
Components for collecting bank account details.
### Components
`IbanElement`
`AuBankAccountElement`
## Address & Contact Elements
### Description
Components for collecting address and contact information.
### Components
`AddressElement`
`ContactDetailsElement`
## Payment Request Elements
### Description
Component for displaying the Payment Request button.
### Component
`PaymentRequestButtonElement`
## Express Checkout Elements
### Description
Components for express checkout flows.
## Issuing Card Display Elements
### Description
Components for displaying issuing card information.
## Tax and Currency Selector Elements
### Description
Components for selecting tax and currency.
```
--------------------------------
### StripeCheckoutFormSdkOptions Interface
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/configuration.md
Defines the configuration options for the Form-based checkout SDK. Includes required clientSecret and optional appearance, fonts, loader, savedPaymentMethod, and defaultValues.
```typescript
interface StripeCheckoutFormSdkOptions {
// Required
clientSecret: string | Promise
// Optional
appearance?: Appearance
fonts?: Font[]
loader?: 'auto' | 'always' | 'never'
savedPaymentMethod?: SavedPaymentMethodOptions
defaultValues?: DefaultValues
}
```
--------------------------------
### Synchronous Stripe Instance Configuration
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/configuration.md
Pass a resolved Stripe instance directly to the Elements component. Ensure the Stripe instance is loaded before rendering.
```typescript
import {Stripe, loadStripe} from '@stripe/stripe-js';
const stripe: Stripe = await loadStripe('pk_test_YOUR_KEY');
// Pass the resolved instance
{/* Components */}
```
--------------------------------
### Bank Account & Payment Method Elements
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/exports.md
Components for handling bank account and payment method inputs.
```APIDOC
## IbanElement
### Description
Component for rendering an IBAN input field.
### Type
FunctionComponent
### Source
`src/index.ts:92-95`
```
```APIDOC
## AuBankAccountElement
### Description
Component for rendering an Australian bank account input field.
### Type
FunctionComponent
### Source
`src/index.ts:43-46`
```
```APIDOC
## LinkAuthenticationElement
### Description
Component for collecting customer email for authentication.
### Type
FunctionComponent
### Source
`src/index.ts:121-124`
```
--------------------------------
### Elements Provider and Hooks
Source: https://github.com/stripe/react-stripe-js/blob/master/_autodocs/README.md
Core Elements provider and related hooks for accessing Stripe and checkout instances.
```APIDOC
## Elements Provider
### Description
Provides Stripe Elements to the rest of your React application.
### Component
`Elements`
## useElements() Hook
### Description
Access the `StripeElements` instance.
### Hook
`useElements()`
## ElementsConsumer Component
### Description
Provides access to the `StripeElements` instance via a render prop.
### Component
`ElementsConsumer`
## useStripe() Hook
### Description
Access the Stripe instance.
### Hook
`useStripe()`
## useCheckoutElements() Hook
### Description
Access the Checkout Elements instance.
### Hook
`useCheckoutElements()`
## useCheckoutForm() Hook
### Description
Access the Checkout Form instance.
### Hook
`useCheckoutForm()`
## useCheckout() Hook (deprecated)
### Description
Deprecated hook for accessing the Checkout instance.
### Hook
`useCheckout()`
```