React Native

Installing the Library

Prerequisites

Steps

  1. Under your app's root directory, install Mixpanel React Native SDK
npm install mixpanel-react-native
  1. Under your application's iOS folder, run
pod install

At this point, you are ready to use the Mixpanel React Native library

Initializing the Library

To start tracking with the library you must first initialize with your project token.

To initialize the library, first add import { Mixpanel } and call Mixpanel.init with your project token as its argument.

import { Mixpanel } from 'mixpanel-react-native';

...
class YourClass extends React.Component {
    constructor(props) {
        super(props);
        this.configMixpanel();
    }

    configMixpanel = async () => {
        this.mixpanel = await Mixpanel.init("Your mixpanel token");
    }
...

Once you've called this method once, you can access mixpanel throughout the rest of your application.

After installing the library into your React Native app, Mixpanel will automatically collect common mobile events. You can enable/ disable automatic collection through your project settings.

Flushing Events

To preserve battery life and customer bandwidth, the Mixpanel library doesn't send the events you record immediately. Instead, it sends batches to the Mixpanel servers every 60 seconds while your application is running, as well as when the application transitions to the background. You can call flush manually if you want to force a flush at a particular moment.

mixpanel.flush();

EU Data Residency

Route data to Mixpanel's EU servers by setting the serverURL property after initializing the client.
For iOS,

mixpanel.serverURL = "https://api-eu.mixpanel.com"

For Android, route data to Mixpanel's EU servers by adding meta-data entries under the <application> tag of your app's AndroidManifest.xml

<meta-data android:name="com.mixpanel.android.MPConfig.EventsEndpoint"
           android:value="https://api-eu.mixpanel.com/track?ip=1" />
<meta-data android:name="com.mixpanel.android.MPConfig.PeopleEndpoint"
           android:value="https://api-eu.mixpanel.com/engage?ip=1" />
<meta-data android:name="com.mixpanel.android.MPConfig.GroupsEndpoint"
           android:value="https://api-eu.mixpanel.com/groups" />

Opting Users Out of Tracking

Client-side tracking of individual user data can be stopped or resumed by controlling a user’s opt-out/opt-in state. Opt-out methods and library configuration settings only affect data sent from a single library instance. Data sent from other sources to Mixpanel’s APIs will still be ingested regardless of whether the user is opted out locally.

The opt-out/opt-in state of a user is controlled by an opt-out flag that is stored in the local storage of the user’s device. If the value of the flag is true, then the user is opted-out and will not be tracked. If the opt-out flag is false, then the user is tracked. The flag is not set when the SDK is initialized, so the initial state is neither opted in nor opted out. Without the flag set, the user will be tracked by default.

To opt a user out of tracking locally, use the optOutTracking method. To resume tracking for an individual user, use optInTracking Call hasOptedOutTracking to check user’s opt-out status locally. By default, an "$opt_in" event is sent every time that a user opts in.

// Check user’s opt-out status locally
let hasOptedOut = await mixpanel.hasOptedOutTracking();
mixpanel.optOutTracking();

// To opt a user out of tracking locally, use the optOutTracking method. Before calling this method call flush() if you want to send all the events or updates to mixpanel otherwise it will be deleted
mixpanel.optOutTracking();

// To opt-in an already opted-out user from tracking. After using this method people updates and track calls will be sent to Mixpanel.
// Opt-in without any parameters
mixpanel.optInTracking();

Opting Users Out of Tracking by Default

Mixpanel’s tracking libraries will send user data by default. Explicitly setting a default opt-out state of true will opt-out all users by default, preventing data from sending unless a user’s opt-out state is set to false.

const mixpanel = await Mixpanel.init('Your mixpanel token', true /* DEFAULT_OPT_OUT */);

Deleting Existing Data

Opting users out of tracking will stop any future tracking. This does not automatically delete data that has already been collected. Mixpanel's deletion API can be used to delete existing data.

Sending Events

We recommend tracking only five to seven events in your application instead of tracking too many things to start. Ideally, you track users going through your initial user experience and one key metric that matters for your application (e.g. YouTube might choose "Watched Video" as a key metric).

Once you've initialized the library, you can track an event using track with the event name and properties.

//Track an event with a property
mixpanel.track('Plan Selected', {'Plan': 'Premium'});

Timing Events

You can track the time it took for an action to occur, such as an image upload or a comment post, using timeEvent. This will mark the "start" of your action, which will be timed until you finish with a track call. The time duration is then recorded in the "Duration" property.

// start the timer for the event "Image Upload"
mixpanel.timeEvent("Image Upload");
//...some time later
mixpanel.track("Image Upload");

Super Properties

It's common to have certain properties that you want to include with each event you send. Generally, these are things you know about the user rather than about a specific event - for example, the user's age, gender, source, or initial referrer.

To make things easier, you can register these properties as super properties. If you tell us just once that these properties are important, we will automatically include them with all events sent. Super properties are saved to local storage, and will persist across invocations of your app. Mixpanel already stores some information as super properties by default; see a full list of Mixpanel default properties here.

To set super properties, call registerSuperProperties

mixpanel.registerSuperProperties({'Plan': 'Mega', 'Cost': '2000'});

The next time you track an event, the super properties you just set will be included as properties.

Super properties are saved to local storage, and will persist between executions of your app.

Setting Super Properties Once and Only Once

If you want to store a super property only once (for example, a date of first login), you can use registerSuperPropertiesOnce. registerSuperPropertiesOnce behaves like registerSuperProperties and has the same interface, but it doesn't override super properties you've already saved.

This means it's safe to call registerSuperPropertiesOnce with the same property multiple times, and it will only set properties if the super property doesn't exist.

mixpanel.registerSuperPropertiesOnce({'Role': 'Admin'});

More for Super Properties

Remove a previously registered super property. unregisterSuperProperty is an alternative to clear all properties, unregistering specific super properties prevents them from being recorded on future events. This operation does not affect the value of other super properties. Any property name that is not registered is ignored.

mixpanel.unregisterSuperProperty('propertyName');

Get user's super properties. getSuperProperties

const superProperties = await mixpanel.getSuperProperties();

Clear all registered properties of user. clearSuperProperties

mixpanel.clearSuperProperties();

Super Properties Live in Local Storage

Our mobile libraries store your super properties in local storage. They will persist so long as the app is installed (between launches and updates). Uninstalling the app will remove that customers super properties.

Managing User Identity

The Mixpanel library will assign a default unique identifier (we call it "distinct_id") to each install of your application. This distinct_id is saved in local storage, and will be the same across executions of your app.

If you choose, you can assign your own user IDs. This is particularly useful if a user is accessing your app on multiple platforms or devices (both web and mobile, for example). To assign your own distinct_ids, you can use identify

// Ensure all future events sent from
// the device will have the distinct_id 13793
mixpanel.identify("13793");

In general, if you use identify, you should call it as soon as the user logs in to your application. This will track all of their authenticated application usage to the correct user ID.

📘

NOTE

Calling identify with a new ID will change the distinctID stored on the device. Updates to user profiles are queued on the device until identify() is called.

Combining Anonymous and Identifiable User Data

It's important to send the same distinct_id with each event that an individual user triggers. Events recorded with different distinct_ids will be treated in Mixpanel as if they were performed by different users.

There are times when it can be convenient to start referring to a user by a different identifier in your implementation. The most common case is after registration, when a user switches from being an anonymous user (with an anonymous distinct_id) to an authenticated user with an (authenticated id). In this case, you can create an alias for the user to keep the distinct_id consistent. An alias is a string stored in a Mixpanel lookup table that is associated with an anonymous distinct_id. Once written, aliases are not editable. Any data sent to Mixpanel with an alias as the distinct_id will be remapped and written to disk using the alias's corresponding anonymous distinct_id. This allows you to start identifying a user by an authenticated id without changing the distinct_id that is ultimately written in Mixpanel.

// This makes the current ID (by default an auto-generated GUID)
// and '13793' interchangeable distinct ids (but not retroactively).
mixpanel.alias("13793", null);
// To create a user profile, you must call identify()
mixpanel.identify(mixpanel.getDistinctId());

The recommended usage pattern is to call both alias and identify when the user signs up (as shown in the example above), and only identify (with the aliased user ID) on future log ins. This will keep your signup funnels working correctly.

📘

NOTE

If you use alias() we recommend only calling it once during the lifetime of the user.

Call Reset at Logout

reset generates a new random distinct_id and clears super properties. Call reset to clear data attributed to a user when that user logs out. This allows you to handle multiple users on a single device. For more information about maintaining user identity, see the Identity Management: Best Practices article.

mixpanel.reset();

Storing User Profiles

In addition to events, you can store user profiles in Mixpanel's Behavioral Analytics product. Profiles are persistent sets of properties that describe a user - things like name, email address, and signup date. You can use profiles to explore and segment users by who they are, rather than what they did.

📘

Before you send profile updates, you must call mixpanel.identify(). The library uses a separate ID for User records, and you must set this value to send updates.

Setting Profile Properties

You can set properties on a user profile with mixpanel.getPeople().set.

// identify must be called before
// user profile properties can be set
mixpanel.identify("13793");

// Sets user 13793's "Plan" attribute to "Premium"
mixpanel.getPeople().set("Plan", "Premium");

This will set a "Plan" property, with a value "Premium", on user 13793's profile. If there isn't a profile with distinct_id 13793 in Mixpanel already, a new profile will be created. If user 13793 already has a property named "Plan" in their profile, the old value will be overwritten with "Premium".

📘

NOTE

Pick your property names wisely. Once you've sent them to Mixpanel, there is no way to change them. Feel free to use capitalization and spaces in between words.
There are a few limitations:

  • Your property names should not begin with $ or mp_. These properties are reserved for special properties sent by Mixpanel.
  • Your property names cannot begin or end with a space as they will automatically be trimmed.
  • Your property names and values cannot be longer than 255 characters. In practice they should be much shorter than that. Property names get cut off by our user interface at about 20 characters.

Click here to see a list of Mixpanel's reserved user profile properties.

Incrementing Numeric Properties

You can use mixpanel.getPeople().increment to change the current value of numeric properties. This is useful when you want to keep a running tally of things, such as games played, messages sent, or points earned.

// Add 500 to the current value of
// "points earned" in Mixpanel
mixpanel.getPeople().increment("points earned", 500);
let properties = {"dollars spent": 17, "credits remaining", -34};
mixpanel.getPeople().increment(properties);

Appending to List Properties

mixpanel.getPeople().append creates an update that adds an item to a list-valued property. The value you send with the append is added to the end of the list. If the property doesn't exist, it will be created with one element list as its value.

//Identify the user profile that is going to be updated
mixpanel.identify("13793");

//Add the color green to the list property "Favorite Colors"
//A new list property is created if it doesn't already exist
mixpanel.getPeople().append("Favorite Colors", "Green");

Other Types of Profile Updates

There are a few other types of profile updates. They can be accessed through the People class, which is accessible via mixpanel.getPeople().

Tracking Revenue

Mixpanel makes it easy to analyze the revenue you make from individual customers. By associating charges with User Analytics profiles, you can compare revenue across different customer segments and calculate customer lifetime value.

You can track a single transaction with mixpanel.getPeople().trackCharge. This call will add transactions to the individual user profile, which will also be reflected in the Mixpanel Revenue report.

// Make identify has been
// called before making revenue updates
mixpanel.identify("13793");

// Tracks $100 in revenue for user 13793
mixpanel.getPeople().trackCharge(100);

// Refund this user 50 dollars
mixpanel.getPeople().trackCharge(-50);

// Tracks $25 in revenue for user 13793
// on the 2nd of january
mixpanel.getPeople().trackCharge(25, {"$time": "2012-01-02T00:00:00"});

Group Analytics

📘

Add Group Keys

To start tracking groups data, add group keys in project settings. If you don't see group keys in your Project Settings, reach out to the Mixpanel Sales Team to purchase Group Analytics.

Mixpanel Group Analytics allows behavioral data analysis by selected groups, as opposed to individual users.

Grouping by identifiers other than the distinct_id will allow analysis at a company or group level when using Mixpanel analytics. Read this article to learn more about Group Analytics.

A group is identified by the group_key and group_id.

  • group_key is the property that connects event data for Group Analytics.
  • group_id is the identifier for a specific group.

If the property “company” is chosen for Group Analytics, “company” is the group_key, and “Mixpanel”, “Company A”, and “13254” are all potential group_id values.

A user can belong to multiple groups. All updates to a group operate on the group_key and group_id.

Creating a Group Key

Administer group keys through your Project Settings. Group keys are event properties. All events need to have a defined group key on them in order to be attributed to a group. Group keys are project specific, and the group key should be set up before group data is sent. Note that Mixpanel does not backfill historical data before the group key was implemented.

To administer group keys, navigate to your Project Settings. Click +Add Group Key under the GROUP KEYS section.

Enter an event property to attribute the group key to. You can also enter a display name for the group key. Click Save.

Adding Users to a Group

Adding users to groups causes the group_key and group_id to send as a property key and value for all events triggered by that user on the device. You can add multiple values for a single user to the group_key list property.

Similar to a distinct_id, the group_key allows Mixpanel to group events by an identifier for analysis. A group_key, however, is a group level identifier and not a user level identifier like the distinct_id.

You can add users to groups by calling the setGroup method.

mixpanel.setGroup("group key", "group id");

You can call addGroup to add any additional groups to an existing list.

mixpanel.addGroup("group key", "group id");

You can call removeGroup to remove any additional groups from an existing list.

mixpanel.removeGroup("group key", "group id");

Creating Group Profiles

It is possible to create a Group profile that is similar to a user profile. You must call getGroup().set()to build a group profile. It is important to the group_key, group_id, and one property so that the profile is not empty.

mixpanel.getGroup(MixpanelToken, "company_id", 12345).set("SET NAME", "SET VALUE");

Setting Group Profile Properties

You can add details to Groups by adding properties to them.

In order to update Group profile properties, you must specify the group that needs to be updated by calling getGroup().set().

mixpanel.getGroup("group key", "group id").set("SET NAME", "SET VALUE");

The getGroup() method can be chained with other commands that edit properties specific to the group.

You can set the property $name to populate the name field at the top of the group profile.

These operations are similar to the corresponding operations for user profile property updates.

set

getGroup().set() updates or adds a property to a group.

mixpanel.getGroup("group key", "group id").set("SET NAME", "SET VALUE");

set once

getGroup().setOnce() adds a property value to a group only if it has not been set before.

mixpanel.getGroup("group key", "group id").setOnce("SET ONCE NAME", "SET ONCE VALUE");

unset

getGroup().unset() unsets a specific property in the group.

mixpanel.getGroup("group key", "group id").unset("UNSET NAME");

remove

getGroup().remove() removes a specific value in a list property.

mixpanel.getGroup("group key", "group id").remove("property name", "value to remove");

union

getGroup().union() adds the specified values to a list property and ensures that those values only appear once.

mixpanel.getGroup("group key", "group id").union("UNION NAME", ["prop_value_a", "prop_value_b"]);

delete

getGroup().deleteGroup() deletes a group.

mixpanel.getGroup("group key", "group id").deleteGroup();

Updated about a month ago

React Native


Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.