Title: React Native SDK Locale: en URL: https://sensorswave.com/en/docs/data-integration/client-sdks/reactnative/ Description: React Native SDK integration guide and API reference Sensors Wave React Native SDK is a mobile data collection and A/B testing tool designed for React Native applications. ## Core Features React Native SDK provides the following core capabilities: - **Event Tracking**: Manually track custom events and user behaviors - **Auto-tracking**: Automatically collect app installation, launch, termination, page view, and click events - **User Identification**: Support anonymous and logged-in user identity association - **User Properties Management**: Complete user properties operations (set, append, increment, etc.) - **A/B Testing Integration**: Support Feature Gates and experiment variable retrieval - **Navigation Tracking**: Full support for React Navigation v6/v7+ with automatic page change tracking - **Batch Sending**: Optimize network request performance, batch send up to 10 events every 5 seconds - **Common Properties**: Support static and dynamic common properties, automatically attached to all events - **React Hooks**: Provide `useSensorswave` hook for easy component usage ## Requirements - **React Native >= 0.74.0** - **React >= 18.0.0** ## Installation ### NPM Installation ```bash npm install @sensorswave/react-native-sdk ``` ### Yarn Installation ```bash yarn add @sensorswave/react-native-sdk ``` ### PNPM Installation ```bash pnpm add @sensorswave/react-native-sdk ``` ## Quick Start ### Basic Initialization Initialize the SDK in your app entry file: ```typescript // Initialize SDK Sensorswave.init('YOUR_SOURCE_TOKEN', { apiHost: 'https://your-api-endpoint.com', // Data reporting endpoint debug: false, // Debug mode autoCapture: true, // Enable auto-tracking enableClickTrack: true, // Enable click auto-tracking enableAB: true, // Enable A/B testing }); ``` ### Wrap App with Provider Use `SensorswaveProvider` to wrap your application and enable automatic navigation tracking: ```tsx const App = () => { return ( ); }; ``` ### Send Your First Event Start tracking events immediately after initialization: ```typescript // Track button click Sensorswave.trackEvent('ButtonClick', { button_name: 'submit', page: 'home' }); ``` ## Configuration Options The second parameter of the `init` method is a configuration object that supports the following options: | Option | Type | Default | Description | |--------|------|---------|-------------| | `apiHost` | `string` | `''` | **Required**, API endpoint for data reporting, available in Pipeline | | `debug` | `boolean` | `false` | Enable debug mode to output detailed logs in console | | `autoCapture` | `boolean` | `true` | Enable auto-tracking to automatically collect app install, launch, end, and page view events | | `enableClickTrack` | `boolean` | `false` | Enable automatic click tracking (track TouchableOpacity, Pressable, Button, etc.) | | `enableAB` | `boolean` | `false` | Enable A/B testing functionality | | `batchSend` | `boolean` | `true` | Use batch sending, send up to 10 events every 5 seconds | | `abRefreshInterval` | `number` | `600000` | A/B testing configuration refresh interval (milliseconds), default 10 minutes | ### Complete Configuration Example ```typescript Sensorswave.init('YOUR_SOURCE_TOKEN', { apiHost: 'https://your-api-endpoint.com', debug: true, // Enable debug in development autoCapture: true, // Enable auto-tracking enableClickTrack: true, // Enable click tracking batchSend: true, // Batch send for performance enableAB: true, // Enable A/B testing abRefreshInterval: 10 * 60 * 1000 // Refresh A/B testing data every 10 minutes }); ``` > **Tip**: It's recommended to disable `debug` mode in production to avoid excessive console output. ## API Methods ### Event Tracking #### trackEvent - Track Custom Events Manually track custom events and their properties. **Parameters**: - `eventName` (string, required): Event name - `properties` (Object, optional): Event properties as key-value pairs **Example**: ```typescript // Track button click Sensorswave.trackEvent('ButtonClick', { button_name: 'submit', page: 'home' }); ``` **Real-world Scenario Examples**: ```typescript // E-commerce scenario: User views product Sensorswave.trackEvent('ProductView', { product_id: '12345', product_name: 'Wireless Bluetooth Headphones', category: 'Electronics', price: 299.00, currency: 'CNY' }); // E-commerce scenario: User adds to cart Sensorswave.trackEvent('AddToCart', { product_id: '12345', quantity: 1, price: 299.00 }); // Content platform: Article reading Sensorswave.trackEvent('ArticleRead', { article_id: 'article_001', title: 'React Native Performance Optimization Tips', category: 'Tech Blog', read_duration: 120 // Reading duration (seconds) }); ``` #### track - Advanced Event Tracking Send a complete event object with more granular control. This method allows you to manually specify all event fields. **Parameters**: - `event` (AdvanceEvent, required): Complete event object containing the following fields: - `event` (string, required): Event name - `properties` (Record, optional): Event properties - `time` (number, required): Timestamp (milliseconds) - `anon_id` (string, optional): Anonymous user ID - `login_id` (string, optional): Logged-in user ID. One of login_id or anon_id must be provided. If both are provided, login_id takes priority - `trace_id` (string, required): Request tracking ID - `user_properties` (Record, optional): User properties **Example**: ```typescript Sensorswave.track({ event: 'purchaseCompleted', properties: { product_id: '12345', amount: 99.99, currency: 'USD' }, time: Date.now(), trace_id: 'unique-trace-id-12345', anon_id: 'anonymous-user-id', login_id: 'user_12345', user_properties: { // $set: Represents inserting or updating a user property $set: { plan: 'premium', signup_date: '2024-01-01' } } }); ``` > **Note**: The `track` method is an advanced feature. For most scenarios, `trackEvent` is sufficient. ### User Identification #### identify - Set Logged-in User ID Set the logged-in user ID and send a binding event to associate anonymous behaviors with the identified user. **Parameters**: - `loginId` (string | number, required): Unique identifier for the user (e.g., email, user ID, username) **Example**: ```typescript // Set user ID after login Sensorswave.identify('user_12345'); ``` **Complete Login Flow Example**: ```typescript // User login flow async function handleUserLogin(email: string, password: string) { try { // Call login API const response = await fetch('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, password }) }); const { userId } = await response.json(); // Set user ID and associate anonymous behaviors Sensorswave.identify(userId); } catch (error) { console.error('Login failed:', error); } } ``` > **Important**: If the `loginId` contains sensitive information (such as phone numbers, email addresses, ID numbers, etc.), please encrypt it before transmission to avoid sending sensitive data in plain text. #### setLoginId - Set Login ID Only Set the logged-in user ID without sending a binding event. Use this method if you only want to identify users without associating them. **Parameters**: - `loginId` (string | number, required): Unique identifier for the user **Example**: ```typescript Sensorswave.setLoginId('user_12345'); ``` > **Important**: If the `loginId` contains sensitive information (such as phone numbers, email addresses, ID numbers, etc.), please encrypt it before transmission to avoid sending sensitive data in plain text. > **Recommendation**: In most cases, using the `identify` method is recommended as it records user identity association events for better analysis. #### getLoginId - Get Current Login ID Get the currently set logged-in user ID. **Returns**: string | undefined **Example**: ```typescript const loginId = Sensorswave.getLoginId(); console.log('Current user ID:', loginId); ``` #### getAnonId - Get Anonymous ID Get the current anonymous user ID. **Returns**: string **Example**: ```typescript const anonId = Sensorswave.getAnonId(); console.log('Anonymous user ID:', anonId); ``` ### User Properties User properties describe user characteristics such as membership level, registration time, preferences, etc. Unlike event properties, user properties are persisted and associated with users. #### profileSet - Set User Properties Set user properties, overwriting existing properties. **Parameters**: - `properties` (Object, required): User properties to set **Example**: ```typescript // Set user properties after registration Sensorswave.profileSet({ name: 'John Doe', age: 30, plan: 'premium' }); ``` #### profileSetOnce - Set Only Once Set user properties only if they don't exist. Existing properties will not be overwritten. **Parameters**: - `properties` (Object, required): User properties to set **Example**: ```typescript // Record first visit information (recorded only once, won't be overwritten) Sensorswave.profileSetOnce({ signup_date: '2024-01-15', initial_referrer: 'google', initial_campaign: 'spring_sale' }); ``` #### profileIncrement - Increment Numeric Properties Increment or decrement numeric user properties. Only supports numeric properties. **Parameters**: - `properties` (Object, required): Properties and their values to increment **Example**: ```typescript // Increment single property Sensorswave.profileIncrement({ login_count: 1 }); // Increment multiple properties Sensorswave.profileIncrement({ login_count: 1, points_earned: 100, purchases_count: 1 }); ``` #### profileAppend - Append to Array Properties Append new values to array-type user properties without deduplication. **Parameters**: - `properties` (Object, required): Properties and their array values to append **Example**: ```typescript Sensorswave.profileAppend({ categories_viewed: ['electronics', 'mobile_phones'], tags: ['new_customer', '2024Q1'] }); ``` #### profileUnion - Append to Set Properties (Deduplicated) Append new values to array-type user properties with automatic deduplication. **Parameters**: - `properties` (Object, required): Properties and their array values to append **Example**: ```typescript // First call Sensorswave.profileUnion({ interests: ['technology', 'gaming'] }); // Second call, 'technology' won't be added again Sensorswave.profileUnion({ interests: ['technology', 'music'] // Only 'music' will be added }); ``` #### profileUnset - Delete Specific Properties Set specified user properties to null. **Parameters**: - `propertyNames` (string | string[], required): Property name or array of property names to set to null **Example**: ```typescript // Handle single property Sensorswave.profileUnset('temporary_campaign'); // Handle multiple properties Sensorswave.profileUnset(['old_plan', 'expired_flag', 'temp_id']); ``` #### profileDelete - Delete All User Properties Delete all user properties for the current user. This operation is irreversible. **Example**: ```typescript // Delete all user properties when account is cancelled Sensorswave.profileDelete(); ``` > **Warning**: `profileDelete` will delete all user properties. Use with caution. #### User Properties Usage Example **Membership Upgrade Scenario**: ```typescript function handleMembershipUpgrade(newPlan: string) { // Update membership level and upgrade time Sensorswave.profileSet({ plan: newPlan, upgrade_time: new Date().toISOString() }); // Increment upgrade count Sensorswave.profileIncrement({ upgrade_count: 1 }); // Track upgrade event Sensorswave.trackEvent('membershipUpgrade', { from_plan: 'basic', to_plan: newPlan }); } ``` ### Common Properties Common properties are automatically added to all events, suitable for generic information that needs to be included in every event. Supports both static properties (string values) and dynamic properties (function return values). #### registerCommonProperties - Register Common Properties Register static or dynamic common properties that will be automatically included in all events. **Parameters**: - `properties` (Record, required): Properties to register - Static properties: string values - Dynamic properties: functions (called each time an event is sent) **Example**: ```typescript Sensorswave.registerCommonProperties({ // Static properties app_version: '1.0.0', environment: 'production', // Dynamic properties (called each time an event is sent) current_time: () => new Date().toISOString(), user_session_id: () => getSessionId(), // User-related dynamic data user_tier: () => getUserTier() }); ``` #### clearCommonProperties - Clear Common Properties Remove specified registered common properties. **Parameters**: - `propertyNames` (string[], required): Array of property names to remove **Example**: ```typescript Sensorswave.clearCommonProperties(['app_version', 'user_session_id']); ``` > **Note**: Common properties increase the data size of each event. It's recommended to only add essential generic properties. ### A/B Testing React Native SDK has built-in A/B testing support to retrieve Feature Gate status and experiment variables. #### Enable A/B Testing ```typescript Sensorswave.init('YOUR_SOURCE_TOKEN', { apiHost: 'https://your-api-endpoint.com', enableAB: true, // Enable A/B testing abRefreshInterval: 10 * 60 * 1000 // Configuration refresh interval (10 minutes) }); ``` #### checkFeatureGate - Check Feature Gate Check if a Feature Gate is enabled for the current user. Returns a Promise that resolves to a boolean. **Parameters**: - `key` (string, required): Feature Gate key **Returns**: Promise **Example**: ```typescript // Check if feature is enabled async function initFeature() { const isEnabled = await Sensorswave.checkFeatureGate('advanced_search'); if (isEnabled) { enableAdvancedSearch(); } } ``` #### getExperiment - Get Experiment Variables Get experiment variable data for the current user. Returns a Promise that resolves to an experiment configuration object. **Parameters**: - `key` (string, required): Experiment key **Returns**: Promise The returned object contains the experiment's variable configuration values (Record). **Example**: ```typescript // Get experiment configuration async function initExperiment() { const experiment = await Sensorswave.getExperiment('pricing_display'); if (experiment) { const { price_format, discount_type } = experiment; updatePricingDisplay(price_format, discount_type); } } ``` **Complete A/B Testing Example**: ```typescript // E-commerce homepage CTA button A/B test async function initHomepageCTA() { try { const experiment = await Sensorswave.getExperiment('homepage_cta_test'); if (experiment) { const { button_text, button_color, button_size } = experiment; // Apply experiment configuration setCTAConfig({ text: button_text || 'Buy Now', color: button_color || '#ff6600', size: button_size || '16px' }); } } catch (error) { console.error('Failed to fetch experiment variables:', error); // Use default configuration } } // Initialize on page load useEffect(() => { initHomepageCTA(); }, []); ``` > **Tip**: A/B testing functionality requires configuring experiments and Feature Gates in the Sensors Wave backend. ## Navigation Tracking SDK provides automatic page view tracking for different navigation scenarios. Choose the method that fits your navigation setup: ### Navigation Tracking Comparison | Navigation Type | Usage | Auto-tracking | Limitations | |----------------|-------|---------------|-------------| | React Navigation v6- | `SensorswaveProvider` | ✅ Yes | None | | React Navigation v7+ | `createNavigationRef()` | ✅ Yes | Requires setting ref | | React Native Navigation (Wix) | Manual `trackScreen()` | ❌ No | Manual call required | | Custom Navigation | Manual `trackScreen()` | ❌ No | Manual call required | ### Method 1: React Navigation v6 and Below (Recommended) Simply wrap your app with `SensorswaveProvider`, no additional configuration needed. ```tsx const Stack = createStackNavigator(); const App = () => { return ( ); }; ``` **How it works**: SDK internally uses `useNavigationState` hook to automatically track route changes. ### Method 2: React Navigation v7+ For React Navigation v7+, use `createNavigationRef` to create a tracked navigation reference: ```tsx const navigationRef = createNavigationRef(); const App = () => { return ( ); }; ``` > **Why this is needed**: React Navigation v7+ changed how navigation state is accessed, requiring a ref-based approach. ### Method 3: Manual Tracking For custom navigation solutions or when automatic tracking is not possible: ```tsx // Call when page changes trackScreen('CustomScreen', { title: 'Custom Page Title', custom_property: 'value', }); ``` ### Custom Page Names You can customize how page names are collected: ```tsx { // Custom page name logic if (name === 'Detail') { return `Product_${params?.productId}`; } return name; }, routeToProperties: (name, params) => ({ // Add custom properties to page view events category: params?.category || 'unknown', }), }, }} > {/* ... */} ``` ### Disable Automatic Page Tracking ```tsx {/* ... */} // or {/* ... */} ``` ## Auto-tracking When auto-tracking is enabled, SDK automatically collects the following event types: | Event Name | Description | Trigger Timing | |-----------|-------------|----------------| | `$AppInstall` | App installation | On first launch after installation | | `$AppStart` | App launch | When app launches or enters foreground | | `$AppEnd` | App termination | When app enters background | | `$AppPageView` | Page view | When navigating to a new page | | `$AppPageLeave` | Page leave | When leaving a page (includes page duration) | When `enableClickTrack` is enabled: | Event Name | Description | Trigger Timing | |-----------|-------------|----------------| | `$AppClick` | Element click | When user clicks an element | ### Enable Auto-tracking ```typescript Sensorswave.init('YOUR_SOURCE_TOKEN', { apiHost: 'https://your-api-endpoint.com', autoCapture: true, // Enable auto-tracking enableClickTrack: true // Enable click auto-tracking }); ``` > **Tip**: Auto-tracking can significantly reduce manual coding effort but increases data volume. Enable selectively based on actual needs. ## Click Tracking ($AppClick) SDK provides automatic click tracking. Enable it by setting `enableClickTrack: true` during initialization. ### Automatically Tracked Components SDK automatically tracks click events for the following React Native components: | Component Type | Example | Description | |---------------|---------|-------------| | **Touchable Components** | TouchableOpacity, TouchableHighlight, TouchableWithoutFeedback | Automatically tracked | | **Pressable** | `` | Automatically tracked | | **Button** | `` | Automatically tracked | ### Basic Usage Simply use components normally, and SDK will automatically track click events: ```tsx Submit Login ``` ### Ignore Component Types Configure which component types to ignore: ```tsx ``` ### Capture Custom Properties Collect custom properties from clicked elements: ```tsx ``` **Effect**: Custom properties will be included in the `$AppClick` event along with standard properties. ### Complete Example ```tsx function App() { return ( ); } function MyScreen() { return ( {/* Auto-tracked - TouchableOpacity */} Submit Form {/* Auto-tracked - Pressable */} Cancel ); } ``` ### Event Data Example Data collected when user clicks a button: ```json { "event": "$AppClick", "properties": { "$screen_name": "FormScreen", "$element_type": "TouchableOpacity", "$element_content": "Submit Form", "$element_selector": "View > TouchableOpacity > Text [Submit Form]", "$element_path": "View > TouchableOpacity > Text > [Submit Form]", "variant": "primary" } } ``` ## React Hooks SDK provides React hooks for easier usage in components. ### useSensorswave Get SDK instance through hook. ```tsx function MyComponent() { const Sensorswave = useSensorswave(); const handlePress = () => { Sensorswave.trackEvent('ButtonPressed', { button: 'my_button', }); }; return ; } ``` ## Best Practices ### Performance Optimization - Avoid calling `trackEvent` frequently in loops, consider merging events or using throttling - Batch sending is enabled by default to effectively reduce network requests - Auto-tracking adds some performance overhead, enable only when needed ### Data Security - Do not pass sensitive information in event properties (such as passwords, credit card numbers, ID numbers) - Keep Source Token secure and avoid exposing it in public code repositories - Ensure data reporting endpoint uses HTTPS protocol ### Platform Compatibility - Supports iOS and Android platforms - Supports React Native 0.74.0 and above - Supports React Navigation v6/v7+ ### Data Loss Risks - Mobile tracking may be affected by network environment, app closure, etc., resulting in some data loss - For critical business data, consider using server-side tracking, see [Tracking Strategy Selection](../tracking-strategy.mdx) - Some events may be lost when the app is force-closed ## FAQ ### Why is my data not being reported successfully? Check the following: 1. **Is Source Token correct**: Confirm that the `sourceToken` parameter is correct 2. **Is data reporting endpoint correct**: Confirm that the `apiHost` configuration is correct 3. **Network connection**: Check if device network connection is normal 4. **Debug mode**: Enable `debug: true` to view console logs 5. **Permission settings**: Confirm app has network access permissions ### How to avoid sending data in development environment? ```typescript const isDevelopment = __DEV__; // React Native environment variable if (!isDevelopment) { Sensorswave.init('YOUR_SOURCE_TOKEN', { apiHost: 'https://your-api-endpoint.com' }); } // Wrap a safe tracking method function trackEvent(eventName: string, properties: Record) { if (!isDevelopment) { Sensorswave.trackEvent(eventName, properties); } else { console.log('[Analytics]', eventName, properties); } } // Usage example trackEvent('ButtonClick', { button_name: 'submit' }); ``` ### Page views not being tracked 1. Ensure `SensorswaveProvider` wraps `NavigationContainer` 2. For React Navigation v7+, use `createNavigationRef()` 3. Check if `autoCapture` is disabled 4. Confirm navigation configuration is correct ### Events not being sent 1. Check if `apiHost` configuration is correct 2. Enable `debug: true` to view logs 3. Check network connection and permissions 4. Confirm SDK is properly initialized ## Related Documentation - [Tracking Strategy Selection](../tracking-strategy.mdx): Learn about the pros and cons of server-side and client-side tracking - [How to Identify Users Correctly](../user-identification.mdx): Best practices for user identification - [Data Model](../data-model.mdx): Understand Sensors Wave's data structure - [Events and Properties](../events-and-properties.mdx): Event design guidelines and best practices --- **Last Updated**: March 27, 2026 **License**: Apache-2.0