NAV
Javascript (ES6)

Introduction to React Native SDK

Welcome to the Flagship React Native SDK documentation!

The following documentation helps you to run Flagship on your React Native environment (iOS or Android).

React Native Flagship SDK provides a <FlagshipProvider/>, making Flagship features available to your apps (ios/android). Flagship features are accessible using Flagship hooks, have a look to the documentation for details.

Prerequisites

Good to know

Getting Started

// 1. **Install** the node module:
npm install @flagship.io/react-native-sdk

// 2. Import the Flagship React provider:
// In most of case, you want to wrap all your app with this provider, so you might put it in your `App.js` file.

import React from 'react';
import FlagshipProvider from '@flagship.io/react-native-sdk';

const App = () => (

        <FlagshipProvider>{/* [...] */}</FlagshipProvider>
    
);
// 3. Initialize the provider:
// You must put at least required props such as 'envId', 'visitorData'.

import React from 'react';
import { FlagshipProvider } from '@flagship.io/react-native-sdk';

const App = () => (
    
        <FlagshipProvider
            envId="bn1ab7m56qolupi5sa0g"
            visitorData={{
                id: 'test-visitor-rn-id',
                context: {}
            }}
            config={{
                fetchNow: true,
                enableConsoleLogs: true
            }}
        >
            {/* [...] */}
        </FlagshipProvider>
    
);

// 4. Use a Flagship hook in a component:
// In most case, you will get the desired modifications.
import React from 'react';
import { useFsModifications } from '@flagship.io/react-native-sdk';

export const MyReactComponent = () => {
    const fsModifications = useFsModifications([
        {
            key: 'backgroundColor',
            defaultValue: 'green',
            activate: false
        }
    ]);
    return (
        <div
            style={{
                height: '200px',
                width: '200px',
                backgroundColor: fsModifications.backgroundColor
            }}
        >
            {"I'm a square with color=" + fsModifications.backgroundColor}
        </div>
    );
};

There are 4 steps to follow to get started with the React SDK. You can check some code example on the right.

  1. Install the node module
  2. Import the Flagship React provider
    In most of case, you want to wrap all your app with this provider, so you might put it in your App.js file.
  3. Initialize the provider
    You must put at least required props such as envId, visitorData.
  4. Use a Flagship hook in a component
    In most case, you will get the desired modifications.

FlagshipProvider Props

All props

These are all available props you can use inside the FlagshipProvider react component:

Props Type Default Description
envId string *required* Your Flagship environment id.
visitorData object *required* This is the data to identify the current visitor using your app.
The visitorData object takes the following attributes:
Argument Type Description
id string Required. The id of the visitor
context object Optional. Your Flagship visitor context you'll set inside attributes. It should match those defined in your campaigns to target your users on it.
config object {} This is the settings of the SDK. It takes an object, the shape is described below.
onInitStart function():void null Callback function called when the SDK starts initialization.
onInitDone function():void null Callback function called when the SDK ends initialization.
onUpdate function(object):void null Callback function called when the SDK is updated. For example, after a synchronize is triggered or a visitor context has changed.
It has one argument which is an object with the following shape:
Key/Property Description
fsModifications It contains the last modifications saved in cache.
initialModifications Array(object) undefined This is an array of modifications where each element must be same shape as element inside "campaigns" attribute.
Providing this prop avoid the SDK to have an empty cache during first initialization.
If the shape of an element is not correct, an error log will give the reason why.
loadingComponent React.ReactNode undefined This component will be rendered when Flagship is loading at first initialization only.
By default, the value is undefined. It means it will display your app and it might display default modifications value for a very short moment.
fetchNow boolean false Decide to fetch automatically modifications when SDK is initialized.
activateNow boolean false Decide to trigger automatically the data when SDK is initialized.
Note: when set to true, it will implicitly set fetchNow=true as well.
enableConsoleLogs boolean false Enable it to display logs on the console when SDK is running.
This will only display logs such as Warnings, Errors, Fatal errors and Info.
enableSafeMode boolean false Enable it to run the SDK into a safe mode when an error might occurs through the SDK.
When safe mode is triggered, default modifications will be returned and other function will just be executed without doing anything.
NOTE: This feature is currently catching errors globally (SDK + your app) which might leads to unexpected SDK safe mode if the error comes from your app. We're working on that issue.
enableErrorLayout boolean false This is a small layout visible at the bottom of the screen. It is displayed only when an unexpected error occurred in the SDK. By default, it's set to false and if set to true, it will be only visible in a node environment other than production. Here a screenshot to have a look.
nodeEnv string 'production' If value is other than production, it will also display Debug logs.
flagshipApi string 'https://decision-api.flagship.io/v1/' This setting can be useful in further scenario:
- If you need to mock the API for tests such as end to end.
- If you want to move to an earlier version the Flagship API (v2, v3,...).
apiKey string null If you want to use the Decision API V2, you must contact the support team so they'll provide you an API Key to authenticate the calls.

Campaign synchronization

Flagship Hooks

Available hooks:

useFlagship

Demo:

import { useFlagship } from '@flagship.io/react-native-sdk';

const fsParams = {
    modifications: {
        requested: [
            {
                key: 'btnColor',
                defaultValue: 'green',
                activate: false
            }
        ]
    }
}

const {
    modifications: fsModifications,
    status: fsStatus,
    hit: fsHit,
} = useFlagship(fsParams);

Demo 2:

import { useFlagship } from '@flagship.io/react-native-sdk';

const { hit: fsHit } = useFlagship();

// insider render function:

<Button
    onClick={() => {
        const mockHit = {
            type: 'Transaction',
            data: {
                transactionId: '12451342423',
                affiliation: 'myAffiliation',
                totalRevenue: 999,
                shippingCost: 888,
                shippingMethod: 'myShippingMethod',
                currency: 'myCurrency',
                taxes: 1234444,
                paymentMethod: 'myPaymentMethod',
                itemCount: 2,
                couponCode: 'myCOUPON',
                documentLocation:
                    'http%3A%2F%2Fabtastylab.com%2F60511af14f5e48764b83d36ddb8ece5a%2F',
                pageTitle: 'myScreen'
            }
        };
        fsHit.send(mockHit);
    }}
>
    Send a transaction hit
</Button>

Most used hook from the Flagship React SDK. Thanks to that hook, you can access to modifications of your current visitor and have an access to the SDK status. Output shape is visible below.

Argument Type description
options object (TS:UseFlagshipParams) See the shape of options param, just below.

useFlagship options

Key/Property Type description
modifications object Node param to specify flagship modifications:
Argument Description
requested Required. An array of object for each modifications following this shape:
Argument Description
key Required. The name of the modification.
defaultValue Required. The default value, if no value found for this modification.
activate Optional.
activateAll Optional. The value is false by default

useFlagship output shape

Key/Property Type description
modifications object An object where each key is a modification with corresponding value
hit object Gives you some functions to send one or further hits:
Key/Property Description
send Takes an object as parameter. The object must follow a hit shape.
sendMultiple Takes an array of object as parameter. Each object must follow a hit shape. You can mix different hit shape within the array.
status object Gives you informations about SDK current sate:
Key/Property Description
isLoading If true, the SDK isn't ready, false otherwise.
lastRefresh Date cast string with ISO format.
This is the date corresponding to the most recent moment where modifications were saved in cache.

Demo:

import { useFlagship } from '@flagship.io/react-native-sdk';

const fsParams = {
    modifications: {
        requested: [
            {
                key: 'btnColor',
                defaultValue: 'green',
                activate: false
            }
        ]
    }
}

const {
    modifications: fsModifications,
    status: fsStatus,
    hit: fsHit,
} = useFlagship(fsParams);

useFsModifications

Demo:

import { useFsModifications } from '@flagship.io/react-native-sdk';

const fsModifications = useFsModifications([
  {
      key: 'btnColor',
      defaultValue: 'green',
      activate: false
  }
]);

This will give you the modification saved in the cache of the SDK.

Argument Type Default description
modificationsRequested Array(object) *required* List of all modifications you're looking for. Each element of the array follow this object structure:
Argument Description
key Required. The name of the modification.
defaultValue Required. The default value, if no value for this modification is found.
activate Optional.
activateAllModifications boolean false If set to true, all modifications will be activated. If set to false, none will be activated.
Be aware that if this argument is set, the attribute activate set in each element of array modificationsRequested will be ignored.

useFsActivate

Demo:

import { useFsModifications } from '@flagship.io/react-native-sdk';

const [toggle, setToggle] = React.useState(false);

useFsActivate(['btnColor', 'otherKey1', 'otherKey2'], [toggle]); // trigger an activate when "toggle" value change.

// insider render function:

<Button
variant="secondary"
onClick={() => setToggle(!toggle)}
>
    Trigger activate
</Button>
Argument Type Default description
modificationKeys Array(string) *required* An array of modification key.
For each key, a http will be done to trigger the activate of corresponding modification.
applyEffectScope Array(string) [] This argument has same behavior as React.useEffect (2nd argument) hook. It will listen values inside the array and trigger a synchronize if one of them have changed. By default it is trigger during the first rendering of the component where it's used.

useFsSynchronize

Demo:

import { useFsActivate } from '@flagship.io/react-native-sdk';

const [toggle, setToggle] = React.useState(false);
const activateAllModifications = false;

useFsSynchronize([toggle], activateAllModifications); // trigger a synchronize when "toggle" value change.

// insider render function:

<Button
variant="secondary"
onClick={() => setToggle(!toggle)}
>
    Trigger synchronize
</Button>

Refresh modifications in cache by making a http request to the Flagship API.

Argument Type Default description
applyEffectScope Array(string) [] This argument has same behavior as React.useEffect (2nd argument) hook. It will listen values inside the array and trigger a synchronize if one of them has changed. By default it is trigger during the first rendering of the component where it's used.
activateAllModifications Boolean false If set to true, all modifications will be activated. If set to false (default behavior), none will be activated.

Demo:

import { useFsSynchronize } from '@flagship.io/react-native-sdk';

const [toggle, setToggle] = React.useState(false);
const activateAllModifications = false;

useFsSynchronize([toggle], activateAllModifications); // trigger a synchronize when "toggle" value change.

// insider render function:

<Button
variant="secondary"
onClick={() => setToggle(!toggle)}
>
    Trigger synchronize
</Button>

Hit Tracking

Available hits

Screen Hit

Demo:

import { useFlagship } from "@flagship.io/react-native-sdk";

const { hit: fsHit } = useFlagship();

<button
  onClick={() => {
    const mockHit = {
        type: 'Screen',
        data: {
          documentLocation: "APP",  /// For the Mobile,  documentLocation = APP
          pageTitle: "blogpost"
        }
    };
    fsHit.send(mockHit);
  }}
>
  Send a screen hit
</button>
Attribute Type Description
documentLocation string Required. Specifies the current URL of the page, at the moment where the hit has been sent.
pageTitle string Required. Specifies the name of the page, at the moment where the hit has been sent.

Transaction Hit

Demo:

import { useFlagship } from "@flagship.io/react-native-sdk";

const { hit: fsHit } = useFlagship();
    
<button
    onClick={() => {
        const mockHit = {
            type: 'Transaction',
            data: {
              transactionId: '101010101',
              affiliation: 'RN_affiliation',
              totalRevenue: 999,
              shippingCost: 888,
              shippingMethod: 'CB',
              currency: '784',
              taxes: 1234444,
              paymentMethod: 'payPal',
              itemCount: 2,
              couponCode: 'myCOUPON',
              documentLocation: "APP",
              pageTitle: 'myScreen'
            }
        };
        fsHit.send(mockHit);
    }}
>
    Send a transaction hit
</button>
Attribute Type Description
transactionId string Required. The id of your transaction.
affiliation string Required. The name of the KPI that you will have inside your reporting.
totalRevenue number Optional. Specifies the total revenue associated with the transaction. This value should include any shipping or tax costs.
shippingCost number Optional. The total shipping cost of your transaction.
shippingMethod string Optional. The shipping method of your transaction.
taxes number Optional. Specifies the total tax of your transaction.
currency string Optional. Specifies the currency of your transaction.
Note: Value should be a valid ISO 4217 currency code.
paymentMethod string Optional. Specifies the payment method used for your transaction.
itemCount number Optional. Specifies the number of item of your transaction.
couponCode string Optional. The coupon code associated with the transaction.
documentLocation string Optional. Specifies the current URL of the page, at the moment where the hit has been sent.
pageTitle string Optional. Specifies the name of the page, at the moment where the hit has been sent.

Item Hit

Demo:

import { useFlagship } from "@flagship.io/react-native-sdk";

const { hit: fsHit } = useFlagship();

<button
  onClick={() => {
    const mockHit = {
        type: "Item",
        data: {
          transactionId: "0987654321",
          name: "RN_item",
          price: 100,
          code: "code",
          category: "category",
          quantity: 123,
          documentLocation: "APP",
        },
    };
    fsHit.send(mockHit);
  }}
>
  Send a item hit
</button>
Attribute Type Description
transactionId string Required. The id of your transaction.
name string Required. The name of your item.
price number Optional. Specifies the price for a single item / unit.
code string Optional. Specifies the SKU or item code.
category string Optional. Specifies the category that the item belongs to.
quantity number Optional. Specifies the number of items purchased.
documentLocation string Optional. Specifies the current URL of the page, at the moment where the hit has been sent.
pageTitle string Optional. Specifies the name of the page, at the moment where the hit has been sent.

Event Hit

Demo:

import { useFlagship } from "@flagship.io/react-native-sdk";

const { hit: fsHit } = useFlagship();

<button
  onClick={() => {
    const mockHit = {
        type: 'Event',
        data: {
          category: 'User Engagement',
          action: 'RN_Onclick',
          label: 'Hello from React Native',
          value: 123,
          documentLocation: "APP"
        }
    };
    fsHit.send(mockHit);
  }}
>
  Send a event hit
</button>
Attribute Type Description
category string Required. Specifies the category of your event.
Note: The value must be either Action Tracking or User Engagement.
action string Required. The name of the KPI you will have inside the reporting.
label string Optional. Specifies additional description of your event.
value number Optional. Specifies how much you won with that event.
For example, depending on the lead generated, you will earn 10 to 100 euros. Adding that value will enable us to do a sum inside the reporting and give you the average value too.
Note: Value must be non-negative.
documentLocation string Optional. Specifies the current URL of the page, at the moment where the hit has been sent.
pageTitle string Optional. Specifies the name of the page, at the moment where the hit has been sent.

Release Notes

1.0.1 (Current version)

Appendix

API Reference (comming soon)