# Mixpanel React Native SDK ## Overview The Mixpanel React Native SDK is the official analytics tracking library for React Native applications, enabling developers to track user behavior, manage user profiles, and analyze group data across iOS and Android platforms. This SDK is a wrapper around Mixpanel's native iOS and Android SDKs, providing offline tracking capabilities and seamless integration with React Native applications. It supports both native mode (leveraging platform-specific SDKs) and JavaScript mode (for Expo and React Native for Web), making it versatile for various React Native deployment scenarios. The library provides a comprehensive suite of analytics features including event tracking with custom properties, user identification and aliasing, People Analytics for user profile management, Group Analytics for tracking organizational entities, super properties that persist across all events, revenue tracking, and opt-in/opt-out functionality for privacy compliance. It automatically collects default properties while allowing developers to enrich events with custom data, time events for duration tracking, and batch network requests for optimal performance. ## APIs and Key Functions ### Initialize Mixpanel Instance Create and initialize a Mixpanel instance with your project token to begin tracking analytics events in your React Native application. ```javascript import { Mixpanel } from "mixpanel-react-native"; // Basic initialization const trackAutomaticEvents = false; const mixpanel = new Mixpanel("YOUR_PROJECT_TOKEN", trackAutomaticEvents); await mixpanel.init(); // Advanced initialization with custom configuration const optOutTrackingDefault = false; const superProperties = { app_version: "1.0.0", environment: "production" }; const serverURL = "https://api-eu.mixpanel.com"; // EU server const useGzipCompression = true; await mixpanel.init( optOutTrackingDefault, superProperties, serverURL, useGzipCompression ); // JavaScript mode for Expo/React Native Web const useNative = false; const mixpanelJS = new Mixpanel("YOUR_PROJECT_TOKEN", false, useNative); await mixpanelJS.init(); ``` ### Track Events Record user actions and behaviors with custom properties to analyze engagement patterns and user flows. ```javascript // Simple event tracking mixpanel.track("Button Clicked"); // Track event with properties mixpanel.track("Product Purchased", { product_id: "12345", product_name: "Premium Subscription", price: 29.99, currency: "USD", category: "subscription" }); // Track event with timing mixpanel.timeEvent("Video Watch"); // ... user watches video ... mixpanel.track("Video Watch", { video_id: "abc123", video_duration: 180 }); // Automatically includes $duration property // Get elapsed time without tracking const elapsed = await mixpanel.eventElapsedTime("Video Watch"); console.log(`Elapsed time: ${elapsed} seconds`); ``` ### Identify Users Associate tracking data with specific users to enable cross-device and cross-session analytics. ```javascript // Identify user after authentication try { await mixpanel.identify("user_12345"); console.log("User identified successfully"); } catch (error) { console.error("Failed to identify user:", error); } // Get current distinct ID const distinctId = await mixpanel.getDistinctId(); console.log(`Current user ID: ${distinctId}`); // Get device ID const deviceId = await mixpanel.getDeviceId(); console.log(`Device ID: ${deviceId}`); // Reset user (logout scenario) mixpanel.reset(); // Clears super properties and generates new distinct ID ``` ### Manage User Profiles with People Analytics Update and manage user profile data to enable targeted messaging and user segmentation. ```javascript const people = mixpanel.getPeople(); // Set user properties (overwrites existing) people.set("email", "user@example.com"); people.set("name", "John Doe"); // Set multiple properties at once people.set({ email: "user@example.com", name: "John Doe", plan: "Premium", signup_date: new Date().toISOString() }); // Set property only once (won't overwrite) people.setOnce("first_login", new Date().toISOString()); // Increment numeric properties people.increment("login_count", 1); people.increment({ page_views: 5, sessions: 1 }); // Append to list properties people.append("favorite_categories", "electronics"); // Union (add unique values to list) people.union("tags", ["vip", "early_adopter"]); // Remove from list people.remove("tags", "trial_user"); // Unset a property people.unset("temp_property"); // Delete user profile people.deleteUser(); ``` ### Track Revenue Monitor transactions and revenue for business intelligence and LTV analysis. ```javascript const people = mixpanel.getPeople(); // Track a purchase people.trackCharge(29.99, { product_name: "Premium Subscription", payment_method: "credit_card", transaction_id: "txn_abc123", $time: new Date().toISOString() }); // Track a refund (negative amount) people.trackCharge(-29.99, { reason: "refund", original_transaction_id: "txn_abc123" }); // Clear all transaction history people.clearCharges(); ``` ### Manage Super Properties Register properties that automatically attach to every tracked event, reducing code duplication and ensuring consistent tracking. ```javascript // Register super properties mixpanel.registerSuperProperties({ app_version: "2.1.0", platform: "mobile", environment: "production" }); // Register only if not already set mixpanel.registerSuperPropertiesOnce({ first_app_version: "2.1.0", install_date: new Date().toISOString() }); // Get current super properties const superProps = await mixpanel.getSuperProperties(); console.log("Current super properties:", superProps); // Remove specific super property mixpanel.unregisterSuperProperty("temp_flag"); // Clear all super properties mixpanel.clearSuperProperties(); ``` ### Group Analytics Track and analyze data at the organization or account level for B2B analytics. ```javascript // Set user's group membership mixpanel.setGroup("company_id", "acme_corp"); // Add user to additional groups mixpanel.addGroup("company_id", "partner_corp"); // Remove from group mixpanel.removeGroup("company_id", "old_corp"); // Track event with specific groups mixpanel.trackWithGroups("Feature Used", { feature_name: "advanced_reporting", usage_count: 5 }, { company_id: "acme_corp", team_id: "engineering" } ); // Get group instance for profile updates const group = mixpanel.getGroup("company_id", "acme_corp"); // Set group properties group.set("plan", "Enterprise"); group.set({ employees: 500, industry: "technology", renewal_date: "2024-12-31" }); // Set once (won't overwrite) group.setOnce("created_date", new Date().toISOString()); // Union list values group.union("features", ["sso", "audit_logs"]); // Remove from list group.remove("features", "beta_feature"); // Unset property group.unset("temp_flag"); // Delete group profile mixpanel.deleteGroup("company_id", "acme_corp"); ``` ### Privacy and Opt-Out Management Implement privacy controls to comply with GDPR, CCPA, and other data protection regulations. ```javascript // Check opt-out status const hasOptedOut = await mixpanel.hasOptedOutTracking(); console.log(`User opted out: ${hasOptedOut}`); // Opt user out (stops all tracking) mixpanel.optOutTracking(); // Opt user back in mixpanel.optInTracking(); // Initialize with opt-out by default const optOutDefault = true; await mixpanel.init(optOutDefault); ``` ### Configuration and Debugging Configure SDK behavior for different environments and troubleshooting scenarios. ```javascript // Enable debug logging mixpanel.setLoggingEnabled(true); // Set custom server URL (e.g., proxy or EU servers) mixpanel.setServerURL("https://api-eu.mixpanel.com"); // Control IP-based geolocation mixpanel.setUseIpAddressForGeolocation(false); // Set flush batch size (max 50) mixpanel.setFlushBatchSize(25); // iOS only: flush when app backgrounds mixpanel.setFlushOnBackground(true); // Manually flush events to server mixpanel.flush(); ``` ### Complete Application Example Full integration example demonstrating initialization, user identification, event tracking, and profile management in a React Native application. ```javascript import React, { useEffect, useState } from "react"; import { View, Button, Text, SafeAreaView, StyleSheet } from "react-native"; import { Mixpanel } from "mixpanel-react-native"; // Initialize outside component for singleton pattern const trackAutomaticEvents = true; const mixpanel = new Mixpanel("YOUR_PROJECT_TOKEN", trackAutomaticEvents); const App = () => { const [userId, setUserId] = useState(null); useEffect(() => { initializeMixpanel(); }, []); const initializeMixpanel = async () => { try { await mixpanel.init(false, { app_version: "1.0.0", platform: "react-native" }); mixpanel.setLoggingEnabled(__DEV__); const distinctId = await mixpanel.getDistinctId(); setUserId(distinctId); console.log("Mixpanel initialized"); } catch (error) { console.error("Mixpanel initialization error:", error); } }; const handleLogin = async (email) => { try { await mixpanel.identify(email); const people = mixpanel.getPeople(); people.set({ $email: email, $name: "John Doe", login_date: new Date().toISOString() }); mixpanel.track("User Logged In", { method: "email", timestamp: Date.now() }); setUserId(email); } catch (error) { console.error("Login tracking error:", error); } }; const handlePurchase = () => { mixpanel.track("Purchase Completed", { product_id: "premium_annual", price: 99.99, currency: "USD" }); const people = mixpanel.getPeople(); people.trackCharge(99.99, { product: "Premium Annual", payment_method: "credit_card" }); people.set("plan", "Premium"); people.increment("lifetime_purchases", 1); }; const handleLogout = () => { mixpanel.track("User Logged Out"); mixpanel.flush(); // Ensure events are sent mixpanel.reset(); setUserId(null); }; return ( Mixpanel Demo User ID: {userId || "Anonymous"}