add-native-feature
Skill1.4k starsChanged 3 months agoMITView on GitHub
Step-by-step guide for adding features requiring JS-to-native bridge communication in the Stripe React Native SDK. Covers TypeScript types, Android Kotlin, iOS Swift, event emitters, bidirectional callbacks, and native module specs.
Trending
Quiet this year.thin dataabout the whole repository
Who's talking about stripe/stripe-react-native
- tipsi/tipsi-stripe“PSA: Stripe's official React Native library is now live 🙌”GitHub · May 12, 2021 · 19 reactions
- flutter-stripe/flutter_stripe“Localization: Allow overriding system locale”GitHub · Nov 14, 2024 · 5 reactions
- stripe/stripe-android“[BUG] CardBrandView change to Composable causes app crashes”GitHub · Jun 13, 2024 · 5 reactions
- naoufal/react-native-payments“👉 Stripe React Native Official SDK 👉”GitHub · Oct 21, 2021 · 5 reactions
- stripe/stripe-android“[BUG] 3DS confirmation screen closed if app is put in background and reopen from app icon”GitHub · Jun 15, 2023 · 4 reactions
The biggest 5 of 10 mentions linking to the repository that our crawl found. Each line is their own headline.
See all 10
Talked about on GitHub and Hacker News (10 times).
On GitHub · 9
- May 12, 2021PSA: Stripe's official React Native library is now live 🙌 — tipsi/tipsi-stripe19 reactions
- Nov 14, 2024Localization: Allow overriding system locale — flutter-stripe/flutter_stripe5 reactions
- Jun 13, 2024[BUG] CardBrandView change to Composable causes app crashes — stripe/stripe-android5 reactions · 14 comments
- Oct 21, 2021👉 Stripe React Native Official SDK 👉 — naoufal/react-native-payments5 reactions · 4 comments
- Jun 15, 2023[BUG] 3DS confirmation screen closed if app is put in background and reopen from app icon — stripe/stripe-android4 reactions · 6 comments
4 more on GitHub
- Dec 23, 2022SDK 47 installs incompatible version of Stripe using managed workflow on Android — expo/expo3 reactions · 2 comments
- Dec 22, 2022Android build fails due to jitpack server is down — expo/expo3 reactions · 14 comments
- Mar 18, 2025[docs] redirectSystemPath return null not documented — expo/expo2 reactions · 8 comments
- Sep 9, 2024[BUG] Preferred network for co-branded cards not working — stripe/stripe-android2 reactions · 5 comments
On Hacker News · 1
- May 11, 2021Stripe-react-native: React Native library for Stripe1 point
In this repository2 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- deflake-testSkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
15 rules. About 0 are common, 7 are distinctive, and 8 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈7
Distinctive · estimate
This author's own choices. Worth a look.
8
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 20
Use this when adding new configuration parameters that flow one-way from JavaScript to native code.
- Very specific: line 24
Add your new parameter to the relevant type definition in src/types/.
- Distinctive: line 85
Use this when native code needs to request data from JavaScript (e.g., fetching client secrets, custom validation).
- Distinctive: line 103
Create the native code that will request data from JavaScript.
- Very specific: line 157
Add your event to the Events type:
- Very specific: line 171
Use EventEmitter<void> if no data is passed from native to JS
- Very specific: line 172
Use EventEmitter<{ param: type }> for simple parameters
- Very specific: line 173
Use EventEmitter<UnsafeObject<any>> for complex objects (use sparingly)
- Distinctive: line 297
Important: Don't forget to clean up listeners when the component unmounts or is reconfigured.
- Very specific: line 384
Solution: Always call .remove() on subscriptions before creating new ones or when unmounting.
- Distinctive: line 399
Problem: Not handling errors in async callbacks.
- Distinctive: line 416
Solution: Ensure UI updates happen on the main thread:
- Very specific: line 425
Problem: Not calling promise.resolve() or promise.reject() in native code.
- Distinctive: line 426
Solution: Always resolve or reject promises, even in error cases.
- Very specific: line 430
Solution: Use UnsafeObject<T> for complex types and validate in native code.
≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
How to add features to React Native SDK
This guide explains how to add new features that require communication between React Native (JavaScript) and native code (iOS/Android). Use this when adding new native functionality, payment methods, or extending existing components with platform-specific capabilities.
Overview
The SDK uses a bidirectional communication pattern:
- Native -> JavaScript: Native code emits events that JavaScript listens for
- JavaScript -> Native: JavaScript invokes callbacks to return data to native code
Part 1: Passing Simple Data to Native SDKs
Use this when adding new configuration parameters that flow one-way from JavaScript to native code.
Step 1: Update TypeScript Types
Add your new parameter to the relevant type definition in src/types/.
Example: Adding onBehalfOf to PaymentSheet.IntentConfiguration
File: src/types/PaymentSheet.ts
export type IntentConfiguration = {
mode: Mode;
paymentMethodTypes?: PaymentMethod.Type[];
onBehalfOf?: string; // New parameter
};Step 2: Parse Parameters in Native Code
Extract the parameter from the bridge arguments and pass it to the native SDK.
Android Implementation
File: android/src/main/java/com/reactnativestripesdk/PaymentSheetManager.kt (or similar)
override fun onCreate() {
// Parse the parameter from arguments
val onBehalfOf = arguments?.getString("onBehalfOf")
// Pass it to the native SDK
val intentConfiguration = PaymentSheet.IntentConfiguration(
mode = mode,
// ... other existing parameters ...
onBehalfOf = onBehalfOf
)
}iOS Implementation
File: ios/StripeSdkImpl+PaymentSheet.swift
guard let intentConfiguration = params["intentConfiguration"] as? NSDictionary else {
// handle error
return
}
// Extract the parameter
let onBehalfOf = intentConfiguration["onBehalfOf"] as? String
// Build the configuration
let intentConfig = PaymentSheet.IntentConfiguration(
mode: mode,
// ... other existing parameters ...
onBehalfOf: onBehalfOf
)Part 2: Implementing Bidirectional Communication
Use this when native code needs to request data from JavaScript (e.g., fetching client secrets, custom validation).
Communication Flow
React Native (JS) -> Registers Event Listener
|
Native Code (iOS/Android) -> Emits Event -> JS Listener Triggered
|
JS Executes Logic (API call, user input, etc.)
|
JS Invokes Native Callback -> Native Code Receives Result
|
Native Code Continues ExecutionStep 1: Emit an Event from Native Code
Create the native code that will request data from JavaScript.
Android Implementation
File: android/src/main/java/com/reactnativestripesdk/ReactNativeCustomerSessionProvider.kt (or similar)
internal var provideSetupIntentClientSecretCallback: CompletableDeferred<String>? = null
override suspend fun provideSetupIntentClientSecret(customerId: String): Result<String> {
return suspendCancellableCoroutine { continuation ->
// Store the continuation to resume later
provideSetupIntentClientSecretCallback = continuation
// Emit the event to JavaScript
stripeSdkModule?.eventEmitter?.emitOnCustomerSessionProviderSetupIntentClientSecret()
}
}iOS Implementation
File: ios/StripeSdkImpl.swift
// Store the continuation as a property
var clientSecretProviderSetupIntentClientSecretCallback: ((String) -> Void)? = nilFile: ios/StripeSdkImpl+CustomerSheet.swift
let intentConfiguration = CustomerSheet.IntentConfiguration(
// ... other parameters ...
setupIntentClientSecretProvider: {
return try await withCheckedThrowingContinuation { continuation in
// Store the continuation to be resumed later
self.clientSecretProviderSetupIntentClientSecretCallback = { clientSecret in
continuation.resume(returning: clientSecret)
}
// Emit the event to JavaScript
self.emitter?.emitOnCustomerSessionProviderSetupIntentClientSecret()
}
}
)Step 2: Define and Implement the Event Emitter
2a. Define the Event Type
File: src/events.ts
Add your event to the Events type:
type Events = {
// ... existing events ...
onCustomerSessionProviderSetupIntentClientSecret: EventEmitter<void>; // No parameters
// OR if you need to pass data:
onCustomerSessionProviderSetupIntentClientSecret: EventEmitter<{
customerId: string;
}>;
};Guidelines:
- Use
EventEmitter<void>if no data is passed from native to JS - Use
EventEmitter<{ param: type }>for simple parameters - Use
EventEmitter<UnsafeObject<any>>for complex objects (use sparingly)
2b. Implement Android Emitter
File: android/src/main/java/com/reactnativestripesdk/EventEmitterCompat.kt
fun emitOnCustomerSessionProviderSetupIntentClientSecret(value: ReadableMap? = null) {
invoke("onCustomerSessionProviderSetupIntentClientSecret", value)
}
// For events with no parameters:
fun emitOnCustomerSessionProviderSetupIntentClientSecret() {
invoke("onCustomerSessionProviderSetupIntentClientSecret")
}2c. Implement iOS Emitter
File: ios/StripeSdkEmitter.swift
@objc public protocol StripeSdkEmitter {
// ... existing methods ...
// For events with parameters:
func emitOnCustomerSessionProviderSetupIntentClientSecret(_ value: [String: Any])
// For events without parameters:
func emitOnCustomerSessionProviderSetupIntentClientSecret()
}Step 3: Define Native Callback Signatures
These are the methods JavaScript will call to return data to native code.
3a. TypeScript Spec
File: src/specs/NativeStripeSdkModule.ts
export interface Spec extends TurboModule {
// ... existing methods ...
clientSecretProviderSetupIntentClientSecretCallback(
setupIntentClientSecret: string
): Promise<void>;
}3b. Android Spec
Android specs are generated from the TypeScript spec during the native build. No checked-in code additions are needed.
3c. iOS Bridge Declaration
File: ios/StripeSdk.mm
RCT_EXPORT_METHOD(clientSecretProviderSetupIntentClientSecretCallback:(nonnull NSString *)setupIntentClientSecret
resolve:(nonnull RCTPromiseResolveBlock)resolve
reject:(nonnull RCTPromiseRejectBlock)reject)
{
[StripeSdkImpl.shared clientSecretProviderSetupIntentClientSecretCallback:setupIntentClientSecret
resolver:resolve
rejecter:reject];
}Step 4: Implement JavaScript Event Listener
Listen for the native event and invoke the callback with the result.
File: src/components/CustomerSheet.tsx (or relevant component)
// Declare the EventSubscription at the top of the file
let setupIntentClientSecretProviderCallback: EventSubscription | null = null;
const configureClientSecretProviderEventListeners = (
clientSecretProvider: ClientSecretProvider
): void => {
// Remove existing listener to prevent duplicates
setupIntentClientSecretProviderCallback?.remove();
// Register the event listener
setupIntentClientSecretProviderCallback = addListener(
'onCustomerSessionProviderSetupIntentClientSecret',
async () => {
try {
// Execute the user-provided function (e.g., API call)
const setupIntentClientSecret =
await clientSecretProvider.provideSetupIntentClientSecret();
// Return the result to native code
await NativeStripeSdk.clientSecretProviderSetupIntentClientSecretCallback(
setupIntentClientSecret
);
} catch (error) {
// Handle errors appropriately
console.error('Failed to provide setup intent client secret:', error);
}
}
);
};If the event includes parameters from native:
setupIntentClientSecretProviderCallback = addListener(
'onCustomerSessionProviderSetupIntentClientSecret',
async ({ customerId }) => { // Destructure parameters
const setupIntentClientSecret =
await clientSecretProvider.provideSetupIntentClientSecret(customerId);
await NativeStripeSdk.clientSecretProviderSetupIntentClientSecretCallback(
setupIntentClientSecret
);
}
);Important: Don't forget to clean up listeners when the component unmounts or is reconfigured.
Step 5: Complete the Native Callback Implementation
Resume the async operation started in Step 1 with the data from JavaScript.
Android Implementation
File: android/src/main/java/com/reactnativestripesdk/StripeSdkModule.kt
override fun clientSecretProviderSetupIntentClientSecretCallback(
setupIntentClientSecret: String,
promise: Promise
) {
customerSheetFragment?.let {
// Resume the coroutine with the result from JavaScript
it.customerSessionProvider?.provideSetupIntentClientSecretCallback?.resume(
Result.success(setupIntentClientSecret)
)
promise.resolve(null)
} ?: run {
promise.reject(
"CustomerSheetNotInitialized",
"Customer Sheet must be initialized before calling this callback"
)
}
}iOS Implementation
File: ios/StripeSdkImpl+CustomerSheet.swift
@objc(clientSecretProviderSetupIntentClientSecretCallback:resolver:rejecter:)
public func clientSecretProviderSetupIntentClientSecretCallback(
setupIntentClientSecret: String,
resolver resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock
) -> Void {
// Resume the continuation with the result from JavaScript
self.clientSecretProviderSetupIntentClientSecretCallback?(setupIntentClientSecret)
// Clear the callback
self.clientSecretProviderSetupIntentClientSecretCallback = nil
resolve([])
}Implementation Checklist
Part 1: Simple Data Passing
- TypeScript types updated in
src/types/ - Android parameter parsing implemented
- iOS parameter parsing implemented
Part 2: Bidirectional Communication
- Event emission added in Android native code
- Event emission added in iOS native code
- Event type defined in
src/events.ts - Android emitter implemented in
EventEmitterCompat.kt - iOS emitter declared in
StripeSdkEmitter.swift - TypeScript callback spec added to
NativeStripeSdkModule.ts - iOS bridge method added to
StripeSdk.mm - JavaScript event listener implemented in component
- Android callback completion implemented in
StripeSdkModule.kt - iOS callback completion implemented in Swift
Testing & Documentation
- Unit tests written for TypeScript code
- Native tests written (iOS XCTest / Android)
- Example app updated to demonstrate feature
- E2E tests written using Maestro
- Code runs without linter errors (
yarn lint) - TypeScript compiles without errors (
yarn typescript) - Tested on both iOS and Android
Common Pitfalls
Memory Leaks
Problem: Forgetting to remove event listeners.
Solution: Always call .remove() on subscriptions before creating new ones or when unmounting.
useEffect(() => {
// Setup listener
const subscription = addListener('myEvent', handler);
return () => {
// Cleanup on unmount
subscription?.remove();
};
}, []);Missing Error Handling
Problem: Not handling errors in async callbacks. Solution: Wrap callback logic in try-catch blocks and handle failures gracefully.
async () => {
try {
const result = await userProvidedFunction();
await NativeStripeSdk.callback(result);
} catch (error) {
console.error('Error:', error);
// Consider how to communicate errors back to native
}
}Thread Safety (iOS)
Problem: Updating UI from background threads. Solution: Ensure UI updates happen on the main thread:
DispatchQueue.main.async {
// UI updates here
}Incomplete Callback Resolution
Problem: Not calling promise.resolve() or promise.reject() in native code.
Solution: Always resolve or reject promises, even in error cases.
Type Mismatches
Problem: TypeScript types don't match native expectations.
Solution: Use UnsafeObject<T> for complex types and validate in native code.
Platform-Specific Considerations
iOS
- Async/Await: Uses Swift continuations (
withCheckedThrowingContinuation) - Callbacks: Stored as optional closures (
((String) -> Void)?) - Threading: UI operations must run on main thread
- Memory: Be careful with retain cycles; use
[weak self]when needed
Android
- Async/Await: Uses Kotlin coroutines and
suspendCancellableCoroutine - Callbacks: Uses
CancellableContinuationorCompletableDeferred - Threading: React Native bridge handles threading automatically
- Lifecycle: Be aware of Activity/Fragment lifecycle when storing callbacks
Additional Resources
- React Native TurboModules: https://reactnative.dev/docs/the-new-architecture/pillars-turbomodules
- Stripe iOS SDK: https://stripe.dev/stripe-ios
- Stripe Android SDK: https://stripe.dev/stripe-android
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

