### Initialize SDK with Basic Setup Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/configuration.md Basic SDK initialization requires only the settings ID. This is the minimum configuration needed to start using the SDK. ```typescript import { Usercentrics } from '@usercentrics/react-native-sdk'; Usercentrics.configure({ settingsId: 'YOUR_SETTINGS_ID' }); ``` -------------------------------- ### Automatically Install Missing Dependencies Source: https://github.com/usercentrics/react-native-sdk/blob/master/README.md Use this script to automatically install all necessary dependencies and tools required for the SDK. This is part of the automated setup process. ```shell npm run auto-setup ``` -------------------------------- ### Install All Dependencies for Sample App Source: https://github.com/usercentrics/react-native-sdk/blob/master/README.md Installs all project dependencies, including those for the root and the sample application. This is a prerequisite for running the sample app. ```shell npm run install-dependencies ``` -------------------------------- ### Run Sample App on iOS Source: https://github.com/usercentrics/react-native-sdk/blob/master/sample/README.md Start the React Native sample application on an iOS simulator or physical device. Ensure Xcode and necessary command-line tools are installed. ```sh npm run ios # or npx react-native run-ios ``` -------------------------------- ### ButtonSettings Constructor and Styling Examples Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/banner-settings.md Shows how to create minimal and fully customized ButtonSettings objects, including examples for different button types and applying them to a ButtonLayout. ```typescript // Minimal button const minimalButton = new ButtonSettings(ButtonType.acceptAll); // Fully customized button const customButton = new ButtonSettings( ButtonType.acceptAll, 'Roboto-Bold', // fontName 16, // textSize '#FFFFFF', // textColorHex '#27AE60', // backgroundColorHex 12, // cornerRadius false // isAllCaps ); // Different styling per button type const acceptButton = new ButtonSettings( ButtonType.acceptAll, 'Roboto-Bold', 16, '#FFFFFF', '#27AE60', 12 ); const denyButton = new ButtonSettings( ButtonType.denyAll, 'Roboto-Bold', 16, '#FFFFFF', '#E74C3C', 12 ); const moreButton = new ButtonSettings( ButtonType.more, 'Roboto-Bold', 14, '#0066CC', undefined, 0 ); const layout = ButtonLayout.row([denyButton, acceptButton]); ``` -------------------------------- ### Start Android Emulator Source: https://github.com/usercentrics/react-native-sdk/blob/master/sample/README.md Use this command to start a specific Android Virtual Device (AVD) before running the app. ```shell emulator -avd ``` -------------------------------- ### Install iOS Pod Dependencies Source: https://github.com/usercentrics/react-native-sdk/blob/master/README.md Installs the necessary CocoaPods dependencies for the iOS project within the sample folder. This command should be run from the `sample` directory. ```shell npx pod-install ``` -------------------------------- ### Run iOS Application Manually Source: https://github.com/usercentrics/react-native-sdk/blob/master/README.md Starts the iOS application using React Native CLI. This command should be run from the `sample` directory after installing pods. ```shell npx react-native run-ios ``` -------------------------------- ### Full Banner Customization Example Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/banner-settings.md Provides a comprehensive example of customizing both the first and second layers, along with general settings and a specific variant name for the banner. ```typescript import { BannerSettings, FirstLayerStyleSettings, SecondLayerStyleSettings, GeneralStyleSettings, UsercentricsLayout, ButtonLayout, ButtonSettings, ButtonType, SectionAlignment, TitleSettings, MessageSettings } from '@usercentrics/react-native-sdk'; const firstLayer = new FirstLayerStyleSettings( UsercentricsLayout.popupBottom, undefined, new TitleSettings(undefined, 24, '#000000', SectionAlignment.center), new MessageSettings(undefined, 14, '#333333', SectionAlignment.left), ButtonLayout.row([ new ButtonSettings(ButtonType.denyAll, undefined, 16, '#FFFFFF', '#E74C3C'), new ButtonSettings(ButtonType.acceptAll, undefined, 16, '#FFFFFF', '#27AE60') ]), '#FFFFFF', 12, '#00000080' ); const secondLayer = new SecondLayerStyleSettings( ButtonLayout.column([ new ButtonSettings(ButtonType.denyAll), new ButtonSettings(ButtonType.save), new ButtonSettings(ButtonType.acceptAll) ]), true ); const general = new GeneralStyleSettings( undefined, undefined, undefined, '#1A1A1A' ); const settings = new BannerSettings( firstLayer, secondLayer, general, 'myCustomVariant' ); await Usercentrics.showFirstLayer(settings); ``` -------------------------------- ### Create Button Settings Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/banner-settings.md Example demonstrating how to create an array of ButtonSettings objects for different button types and arrange them using ButtonLayout.column. ```typescript import { ButtonType, ButtonSettings, ButtonLayout } from '@usercentrics/react-native-sdk'; // Create buttons of each type const buttons = [ new ButtonSettings(ButtonType.acceptAll), new ButtonSettings(ButtonType.denyAll), new ButtonSettings(ButtonType.more), new ButtonSettings(ButtonType.save) ]; const layout = ButtonLayout.column(buttons); ``` -------------------------------- ### Create TitleSettings Instance Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/banner-settings.md Example of instantiating TitleSettings with specific font, size, color, and alignment for the banner title. ```typescript import { TitleSettings, SectionAlignment } from '@usercentrics/react-native-sdk'; const title = new TitleSettings( 'Roboto-Bold', // fontName 24, // textSize '#000000', // textColorHex SectionAlignment.center // textAlignment ); ``` -------------------------------- ### Initialize SDK with Complete Setup Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/configuration.md Initialize the SDK with all available options, including settings ID, ruleset ID, language, logger level, timeouts, version, network mode, consent mediation, and initialization timeout. ```typescript import { Usercentrics, UsercentricsOptions, UsercentricsLoggerLevel, NetworkMode } from '@usercentrics/react-native-sdk'; const options = new UsercentricsOptions({ settingsId: 'YOUR_SETTINGS_ID', ruleSetId: 'YOUR_RULESET_ID', defaultLanguage: 'en', loggerLevel: UsercentricsLoggerLevel.debug, timeoutMillis: 10000, version: '2.27.0', networkMode: NetworkMode.eu, consentMediation: true, initTimeoutMillis: 5000 }); Usercentrics.configure(options); ``` -------------------------------- ### Example Usage of UsercentricsLayout Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/banner-settings.md Configures the banner to use the 'popupBottom' layout. This example shows how to set the layout when initializing FirstLayerStyleSettings. ```typescript import { FirstLayerStyleSettings, UsercentricsLayout } from '@usercentrics/react-native-sdk'; const firstLayer = new FirstLayerStyleSettings( UsercentricsLayout.popupBottom ); ``` -------------------------------- ### Different Configurations per Build Environment Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/configuration.md This example shows how to apply different SDK configurations based on the build environment (development, staging, production). It uses environment variables to determine the active configuration. ```typescript const config = { development: { settingsId: 'DEV_SETTINGS_ID', loggerLevel: UsercentricsLoggerLevel.debug, networkMode: NetworkMode.world }, staging: { settingsId: 'STAGING_SETTINGS_ID', loggerLevel: UsercentricsLoggerLevel.warning, networkMode: NetworkMode.eu }, production: { settingsId: 'PROD_SETTINGS_ID', loggerLevel: UsercentricsLoggerLevel.error, networkMode: NetworkMode.eu } }; const currentConfig = config[process.env.NODE_ENV || 'development']; Usercentrics.configure(currentConfig); ``` -------------------------------- ### Manual Dependency Installation (Root) Source: https://github.com/usercentrics/react-native-sdk/blob/master/README.md Installs dependencies for the root of the project using npm. The `--legacy-peer-deps` flag is used to handle potential peer dependency conflicts. ```shell npm install --legacy-peer-deps ``` -------------------------------- ### BannerLogo Constructor and Usage Example Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/banner-settings.md Demonstrates how to instantiate a BannerLogo object and use it within GeneralStyleSettings. Requires resolving the asset source for the logo path. ```typescript import { Image } from 'react-native'; const logoSource = Image.resolveAssetSource(require('./assets/logo.png')); const logo = new BannerLogo( 'MyCompanyLogo', logoSource, 'https://mycompany.com/logo.png' // Fallback ); // Use in settings const general = new GeneralStyleSettings(undefined, logo); ``` -------------------------------- ### Create MessageSettings Instance Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/banner-settings.md Example of creating a MessageSettings object with custom text and link styles for the banner message. ```typescript import { MessageSettings, SectionAlignment } from '@usercentrics/react-native-sdk'; const message = new MessageSettings( 'Roboto-Regular', // fontName 14, // textSize '#333333', // textColorHex SectionAlignment.left, // textAlignment '#0066CC', // linkTextColorHex true // linkTextUnderline ); ``` -------------------------------- ### Start Metro Bundler Manually Source: https://github.com/usercentrics/react-native-sdk/blob/master/sample/README.md Manually start the Metro JavaScript bundler. This is usually auto-started by `react-native run-android` or `run-ios`, but can be started separately if needed. ```sh npm start ``` -------------------------------- ### Run Sample App on Android Source: https://github.com/usercentrics/react-native-sdk/blob/master/sample/README.md Start the React Native sample application on an Android device or emulator. Ensure a device/emulator is connected and running. ```sh npm run android # or npx react-native run-android ``` -------------------------------- ### Example: Building and Saving TCF User Decisions Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/tcf-data.md Illustrates how to construct TCF user decisions for purposes, special features, and vendors, and then save them using the SDK. Ensure all necessary types are imported. ```typescript import { TCFUserDecisions, TCFUserDecisionOnPurpose, TCFUserDecisionOnSpecialFeature, TCFUserDecisionOnVendor, AdTechProviderDecision } from '@usercentrics/react-native-sdk'; // Build decisions from user UI interactions const purposeDecisions = [ new TCFUserDecisionOnPurpose(1, true, false), // Purpose 1: consent yes, LI no new TCFUserDecisionOnPurpose(2, true, true), // Purpose 2: both yes new TCFUserDecisionOnPurpose(3, false, false), // Purpose 3: both no ]; const specialFeatureDecisions = [ new TCFUserDecisionOnSpecialFeature(1, true), // SF1: opt-in new TCFUserDecisionOnSpecialFeature(2, false), // SF2: opt-out ]; const vendorDecisions = [ new TCFUserDecisionOnVendor(1, true, false), // Vendor 1: consent yes, LI no new TCFUserDecisionOnVendor(2, true, true), // Vendor 2: both yes ]; const adTechDecisions = [ new AdTechProviderDecision(1, true), // Google SA: consented new AdTechProviderDecision(2, false), // Google Other: not consented ]; const decisions = new TCFUserDecisions( purposeDecisions, specialFeatureDecisions, vendorDecisions, adTechDecisions ); // Save these decisions const consents = await Usercentrics.saveDecisionsForTCF( decisions, TCFDecisionUILayer.secondLayer, [], // Additional service decisions UsercentricsConsentType.explicit ); ``` -------------------------------- ### Log Configuration at Startup Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/configuration.md This example configures the logger level based on the development environment. It sets the logger to 'debug' during development and 'error' in production to manage log verbosity. ```typescript Usercentrics.configure({ loggerLevel: __DEV__ ? UsercentricsLoggerLevel.debug : UsercentricsLoggerLevel.error }); ``` -------------------------------- ### ButtonLayout Factory Method Examples Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/banner-settings.md Illustrates creating different button layouts (row, column, grid) using the factory methods and applying a row layout to FirstLayerStyleSettings. ```typescript import { ButtonLayout, ButtonSettings, ButtonType } from '@usercentrics/react-native-sdk'; // Row layout: buttons side-by-side const rowLayout = ButtonLayout.row([ new ButtonSettings(ButtonType.denyAll), new ButtonSettings(ButtonType.acceptAll) ]); // Column layout: buttons stacked vertically const columnLayout = ButtonLayout.column([ new ButtonSettings(ButtonType.acceptAll), new ButtonSettings(ButtonType.more), new ButtonSettings(ButtonType.denyAll) ]); // Grid layout: multiple rows const gridLayout = ButtonLayout.grid([ [ new ButtonSettings(ButtonType.denyAll), new ButtonSettings(ButtonType.acceptAll) ], [ new ButtonSettings(ButtonType.save) ] ]); // Use in first layer const firstLayer = new FirstLayerStyleSettings( undefined, undefined, undefined, undefined, rowLayout ); ``` -------------------------------- ### BannerFont Configuration Examples Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/banner-settings.md Configures the font properties for banner text, including regular and bold font names, and font size. Examples show usage with system fonts, custom fonts, and platform-specific selections. ```typescript class BannerFont { regularFont: string; boldFont: string; fontSize: number; } ``` ```typescript // Using system fonts const font1 = new BannerFont('System', 'System', 16); // Using custom fonts const font2 = new BannerFont('Roboto-Regular', 'Roboto-Bold', 14); // Using platform-specific fonts const font3 = new BannerFont( Platform.select({ ios: '-apple-system', android: 'sans-serif' }), Platform.select({ ios: '-apple-system', android: 'sans-serif' }), 16 ); ``` -------------------------------- ### First Layer Styling Example Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/banner-settings.md Illustrates how to configure `FirstLayerStyleSettings` with specific layout, header image, title, message, button arrangements, and color schemes. ```typescript const firstLayer = new FirstLayerStyleSettings( UsercentricsLayout.sheet, HeaderImageSettings.extended(myLogo), new TitleSettings('Privacy Settings', 20, '#000000', SectionAlignment.center), new MessageSettings('This site uses cookies...', 14, '#333333'), ButtonLayout.column([ new ButtonSettings(ButtonType.acceptAll), new ButtonSettings(ButtonType.more), new ButtonSettings(ButtonType.denyAll) ]), '#FFFFFF', 16, '#00000099' ); await Usercentrics.showFirstLayer( new BannerSettings(firstLayer) ); ``` -------------------------------- ### Example Usage of GeolocationRuleset Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/consent-data.md Shows how to check for and utilize the GeolocationRuleset from the SDK status to determine active settings and banner requirements for a given location. ```typescript const status = await Usercentrics.status(); if (status.geolocationRuleset) { console.log(`Settings for location: ${status.geolocationRuleset.activeSettingsId}`); if (!status.geolocationRuleset.bannerRequiredAtLocation) { console.log('Banner not required for this location'); // Skip showing consent banner } else { console.log('Banner required for this location'); // Show consent banner } } ``` -------------------------------- ### Run Android Application Manually Source: https://github.com/usercentrics/react-native-sdk/blob/master/README.md Starts the Android application using React Native CLI. Ensure your Android SDK is configured. This command should be run from the `sample` directory. ```shell npx react-native run-android ``` -------------------------------- ### Example Usage of LegalLinksSettings Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/banner-settings.md Sets LegalLinksSettings to 'both' to ensure legal links are visible on both banner layers. This is configured within the GeneralStyleSettings. ```typescript import { GeneralStyleSettings, LegalLinksSettings } from '@usercentrics/react-native-sdk'; const general = new GeneralStyleSettings( undefined, undefined, LegalLinksSettings.both // Show on both layers ); ``` -------------------------------- ### Initialize Usercentrics SDK Source: https://github.com/usercentrics/react-native-sdk/blob/master/sample/README.md Initialize the Usercentrics SDK with settings ID and enable consent mediation if needed. This is done once on app start. ```tsx // Set to true when testing consent mediation. Keep false for normal builds. const MEDIATION_TEST_ENABLED = true; const SETTINGS_ID = '3C9-yvno8-dEzy'; React.useEffect(() => { Usercentrics.configure({ settingsId: SETTINGS_ID, loggerLevel: UsercentricsLoggerLevel.debug, consentMediation: MEDIATION_TEST_ENABLED, }); }, []); ``` -------------------------------- ### Example: Processing TCF Stacks and Purposes Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/tcf-data.md Demonstrates how to retrieve TCF data and process stacks versus individual purposes. This is useful for simplifying the first layer of consent disclosure. ```typescript const tcfData = await Usercentrics.getTCFData(); // Show stacks instead of individual purposes for first layer tcfData.stacks.forEach(stack => { console.log(`Stack: ${stack.name}`); console.log(` Description: ${stack.description}`); console.log(` Purposes: ${stack.purposeIds.join(', ')}`); console.log(` Special Features: ${stack.specialFeatureIds.join(', ')}`); }); // Identify purposes that are part of stacks const stackedPurposes = new Set(); tcfData.stacks.forEach(stack => { stack.purposeIds.forEach(id => stackedPurposes.add(id)); }); // Show individual purposes only if not in a stack tcfData.purposes.forEach(purpose => { if (!stackedPurposes.has(purpose.id)) { console.log(`Individual purpose: ${purpose.name}`); } }); ``` -------------------------------- ### Complete TCF Data Workflow Example Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/tcf-data.md This snippet shows how to retrieve TCF data, present it to the user, collect their decisions, save those decisions, and then retrieve the updated TC string. ```typescript import { Usercentrics, TCFDecisionUILayer, UsercentricsConsentType, TCFUserDecisions } from '@usercentrics/react-native-sdk'; // 1. Retrieve complete TCF data const tcfData = await Usercentrics.getTCFData(); console.log(`TC String: ${tcfData.tcString}`); // 2. Present data to user in your UI console.log(`Total vendors: ${tcfData.vendors.length}`); console.log(`Total purposes: ${tcfData.purposes.length}`); // 3. Collect user decisions const userPurposeDecisions = tcfData.purposes.map(p => new TCFUserDecisionOnPurpose(p.id, true, false) ); const userVendorDecisions = tcfData.vendors.map(v => new TCFUserDecisionOnVendor(v.id, true, false) ); const userSpecialFeatureDecisions = tcfData.specialFeatures.map(sf => new TCFUserDecisionOnSpecialFeature(sf.id, true) ); // 4. Save decisions const decisions = new TCFUserDecisions( userPurposeDecisions, userSpecialFeatureDecisions, userVendorDecisions, [] // Ad tech providers ); const savedConsents = await Usercentrics.saveDecisionsForTCF( decisions, TCFDecisionUILayer.secondLayer, [], UsercentricsConsentType.explicit ); console.log(`Saved ${savedConsents.length} service consents`); // 5. Retrieve updated TC string for transmission const updatedTCFData = await Usercentrics.getTCFData(); console.log(`Updated TC String: ${updatedTCFData.tcString}`); ``` -------------------------------- ### Complete Consent Workflow Example Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/consent-data.md This snippet shows how to initialize the Usercentrics SDK, check its status, restore a user session if available, display the consent banner, and handle user interactions with the first and second layers. It also demonstrates saving user decisions and retrieving consent status. ```typescript import React, { useEffect, useState } from 'react'; import { View, Text } from 'react-native'; import AsyncStorage from '@react-native-async-storage/async-storage'; import { Usercentrics, UsercentricsConsentType, UsercentricsUserInteraction, UserDecision, UsercentricsReadyStatus } from '@usercentrics/react-native-sdk'; export const ConsentManager = () => { const [status, setStatus] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { initializeConsent(); }, []); const initializeConsent = async () => { try { // 1. Configure SDK Usercentrics.configure({ settingsId: 'YOUR_SETTINGS_ID', defaultLanguage: 'en' }); // 2. Check SDK status const currentStatus = await Usercentrics.status(); setStatus(currentStatus); // 3. Check if restoration needed const savedControllerId = await AsyncStorage.getItem('userControlId'); if (savedControllerId && !currentStatus.shouldCollectConsent) { // Session exists, no new consent needed console.log('Restoring user session'); await Usercentrics.restoreUserSession(savedControllerId); } else if (currentStatus.shouldCollectConsent) { // Consent needed, show banner console.log('Showing consent banner'); await showConsentBanner(); } } catch (error) { console.error('Consent initialization error:', error); } finally { setLoading(false); } }; const showConsentBanner = async () => { try { const response = await Usercentrics.showFirstLayer(); // Save controller ID await AsyncStorage.setItem('userControlId', response.controllerId); // Handle different interaction types if (response.userInteraction === UsercentricsUserInteraction.granular) { // User went to second layer for granular decisions await showSecondLayerIfNeeded(); } // Verify consent decisions const consents = await Usercentrics.getConsents(); const acceptedCount = consents.filter(c => c.status).length; console.log(`Consent collected: ${acceptedCount}/${consents.length} services accepted`); } catch (error) { console.error('Error showing consent banner:', error); } }; const showSecondLayerIfNeeded = async () => { try { const response = await Usercentrics.showSecondLayer(); console.log('Second layer interaction:', response.userInteraction); } catch (error) { console.error('Error showing second layer:', error); } }; const handleManualDecision = async (serviceId: string, accepted: boolean) => { try { const decision = new UserDecision(serviceId, accepted); await Usercentrics.saveDecisions( [decision], UsercentricsConsentType.explicit ); console.log(`${serviceId}: ${accepted ? 'Accepted' : 'Denied'}`); } catch (error) { console.error('Error saving decision:', error); } }; if (loading) { return Initializing...; } return ( Consent collected: {status?.shouldCollectConsent ? 'No' : 'Yes'} Location: {status?.location.countryCode} ); }; ``` -------------------------------- ### Example: Creating TCF Purpose Decisions Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/tcf-data.md Shows how to instantiate TCFUserDecisionOnPurpose objects to represent different user choices for a purpose, including consent, legitimate interest, or undecided states. ```typescript // User accepted purpose 2 but only via legitimate interest, not consent const purposeDecision = new TCFUserDecisionOnPurpose(2, false, true); // User denied all decisions for purpose 5 const deniedDecision = new TCFUserDecisionOnPurpose(5, false, false); // User hasn't decided on purpose 7 yet const undecidedDecision = new TCFUserDecisionOnPurpose(7); ``` -------------------------------- ### Example Usage of ToggleStyleSettings Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/banner-settings.md Instantiates ToggleStyleSettings with specific color values for different states. This is then used within GeneralStyleSettings to apply the custom toggle appearance to the banner. ```typescript import { ToggleStyleSettings } from '@usercentrics/react-native-sdk'; const toggleStyle = new ToggleStyleSettings( '#27AE60', // activeBackgroundColorHex (green when on) '#CCCCCC', // inactiveBackgroundColorHex (gray when off) '#E8E8E8', // disabledBackgroundColorHex (light gray when disabled) '#FFFFFF', // activeThumbColorHex (white thumb on green) '#666666', // inactiveThumbColorHex (dark gray thumb on gray) '#999999' // disabledThumbColorHex ); const general = new GeneralStyleSettings( undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, toggleStyle ); ``` -------------------------------- ### ButtonLayout Example: Row Layout Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/types.md Creates a button layout with buttons arranged in a single row. This is useful for simple button arrangements like accept and deny actions. ```typescript const layout = ButtonLayout.row([ new ButtonSettings(ButtonType.acceptAll), new ButtonSettings(ButtonType.denyAll) ]); ``` -------------------------------- ### Secure Storage of Settings ID Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/configuration.md This example shows how to use environment variables to securely store your settings ID instead of hardcoding it directly in the code. A fallback ID is provided for development or testing purposes. ```typescript const settingsId = process.env.USERCENTRICS_SETTINGS_ID || 'FALLBACK_ID'; Usercentrics.configure({ settingsId: settingsId }); ``` -------------------------------- ### Accessing TCF Vendor Restrictions Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/tcf-data.md Demonstrates how to retrieve TCF data and iterate through vendors to identify and log their restrictions. This example shows how to map restriction types to human-readable strings. ```typescript const tcfData = await Usercentrics.getTCFData(); // Find vendors with restrictions tcfData.vendors.forEach(vendor => { if (vendor.restrictions.length > 0) { console.log(`Vendor "${vendor.name}" has restrictions:`); vendor.restrictions.forEach(restriction => { const typeStr = restriction.restrictionType === 0 ? 'Not Allowed' : restriction.restrictionType === 1 ? 'Require Consent' : 'Require Legitimate Interest'; console.log(` Purpose ${restriction.purposeId}: ${typeStr}`); }); } }); ``` -------------------------------- ### Complete Banner Customization Example Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/banner-settings.md Demonstrates how to configure and display fully customized first and second layer banners using the Usercentrics React Native SDK. This includes setting up fonts, logos, general styles, and specific button layouts for both layers. ```typescript import React from 'react'; import { Image, Platform } from 'react-native'; import { Usercentrics, BannerSettings, FirstLayerStyleSettings, SecondLayerStyleSettings, GeneralStyleSettings, BannerFont, BannerLogo, UsercentricsLayout, ButtonLayout, ButtonSettings, ButtonType, TitleSettings, MessageSettings, HeaderImageSettings, SectionAlignment, ToggleStyleSettings, LegalLinksSettings } from '@usercentrics/react-native-sdk'; const showCustomizedBanners = async () => { // Assets const logoSource = Image.resolveAssetSource(require('./logo.png')); // Font configuration const font = new BannerFont( Platform.select({ ios: '-apple-system', android: 'sans-serif' }), Platform.select({ ios: '-apple-system', android: 'sans-serif-condensed' }), 14 ); // Logo configuration const logo = new BannerLogo('MyCompanyLogo', logoSource); // General styling const generalSettings = new GeneralStyleSettings( font, logo, LegalLinksSettings.both, '#1A1A1A', // text '#FFFFFF', // primary background '#F5F5F5', // secondary background '#0066CC', // links '#3498DB', // tabs '#CCCCCC', // borders new ToggleStyleSettings( '#27AE60', '#E0E0E0', '#AAAAAA', '#FFFFFF', '#666666', '#999999' ), false ); // First layer const firstLayerSettings = new FirstLayerStyleSettings( UsercentricsLayout.popupBottom, HeaderImageSettings.logo(logo, 60, SectionAlignment.center), new TitleSettings('Privacy Settings', 20, '#000000', SectionAlignment.center), new MessageSettings('We respect your privacy...', 14, '#333333'), ButtonLayout.row([ new ButtonSettings(ButtonType.denyAll, undefined, 14, '#FFFFFF', '#E74C3C', 8), new ButtonSettings(ButtonType.acceptAll, undefined, 14, '#FFFFFF', '#27AE60', 8) ]), '#FFFFFF', 16, '#00000099' ); // Second layer const secondLayerSettings = new SecondLayerStyleSettings( ButtonLayout.column([ new ButtonSettings(ButtonType.denyAll, undefined, 14), new ButtonSettings(ButtonType.save, undefined, 14), new ButtonSettings(ButtonType.acceptAll, undefined, 14) ]), true ); // Combine all settings const bannerSettings = new BannerSettings( firstLayerSettings, secondLayerSettings, generalSettings ); // Show the customized banners try { const response = await Usercentrics.showFirstLayer(bannerSettings); console.log('User interaction:', response.userInteraction); } catch (error) { console.error('Error showing banner:', error); } }; ``` -------------------------------- ### Typical Initialization Sequence Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/configuration.md This snippet shows the complete initialization process for the SDK, including configuration, checking consent status, and displaying the UI if needed. It also demonstrates how to restore previous consent decisions. ```typescript import React, { useEffect } from 'react'; import { Usercentrics, UsercentricsLoggerLevel, NetworkMode } from '@usercentrics/react-native-sdk'; export const App = () => { useEffect(() => { // 1. Configure the SDK Usercentrics.configure({ settingsId: 'YOUR_SETTINGS_ID', defaultLanguage: 'en', loggerLevel: UsercentricsLoggerLevel.debug, networkMode: NetworkMode.eu, consentMediation: true, initTimeoutMillis: 5000 }); // 2. Check if consent collection is needed const checkConsent = async () => { try { const status = await Usercentrics.status(); if (status.shouldCollectConsent) { // 3. Show consent UI to user const response = await Usercentrics.showFirstLayer(); console.log('User consent collected:', response.controllerId); // 4. Store controller ID for later restoration await AsyncStorage.setItem('userControlId', response.controllerId); } else { console.log('User already gave consent'); // Load existing consent decisions const consents = await Usercentrics.getConsents(); console.log('Existing consents:', consents); } } catch (error) { console.error('Error during consent initialization:', error); } }; checkConsent(); }, []); return ; }; ``` -------------------------------- ### Run Android App from Sample Project Source: https://github.com/usercentrics/react-native-sdk/blob/master/README.md Builds and runs the Android application from the sample project. Ensure your Android environment is set up correctly. ```shell npm run run-android ``` -------------------------------- ### Run iOS App from Sample Project Source: https://github.com/usercentrics/react-native-sdk/blob/master/README.md Builds and runs the iOS application from the sample project. This command is only available on macOS. ```shell npm run ios ``` -------------------------------- ### Get GPP String Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/usercentrics.md Retrieves the encoded GPP string or null if GPP is not applicable for the current user's location. Use this to get the GPP string directly. ```typescript const gppString = await Usercentrics.getGPPString(); if (gppString) { console.log('GPP String:', gppString); } else { console.log('GPP not applicable for this user'); } ``` -------------------------------- ### Get DPS Metadata Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/usercentrics.md Retrieves metadata for a specific Data Processing Service (DPS) using its template ID. Use this to get details about a particular service's data processing. ```typescript const metadata = await Usercentrics.getDpsMetadata('google_analytics'); if (metadata) { console.log('Service metadata:', metadata); } ``` -------------------------------- ### Minimal Banner Customization Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/banner-settings.md Demonstrates how to initialize and use BannerSettings with minimal configuration for showing the first layer. ```typescript import { BannerSettings } from '@usercentrics/react-native-sdk'; const bannerSettings = new BannerSettings(); const response = await Usercentrics.showFirstLayer(bannerSettings); ``` -------------------------------- ### Get All Service Consents Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/usercentrics.md Retrieves an array of all services and their current consent status, including consent history and metadata. ```typescript const consents = await Usercentrics.getConsents(); consents.forEach(service => { console.log(`${service.dataProcessor} - Consent: ${service.status}`); console.log(` Essential: ${service.isEssential}`); console.log(` Version: ${service.version}`); }); ``` -------------------------------- ### Example Usage of SectionAlignment Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/banner-settings.md Demonstrates applying SectionAlignment to TitleSettings and MessageSettings. This controls the horizontal alignment of text elements in the banner. ```typescript import { SectionAlignment, TitleSettings, MessageSettings } from '@usercentrics/react-native-sdk'; const title = new TitleSettings(undefined, 24, undefined, SectionAlignment.center); const message = new MessageSettings(undefined, 14, undefined, SectionAlignment.left); ``` -------------------------------- ### Get A/B Testing Variant Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/usercentrics.md Retrieves the current A/B testing variant assigned to the user, or null if no variant is assigned. ```typescript const variant = await Usercentrics.getABTestingVariant(); if (variant) { console.log(`User is in variant: ${variant}`); } ``` -------------------------------- ### Get Usercentrics SDK Status Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/usercentrics.md Retrieves the current ready status of the SDK. This method waits until the SDK initialization is complete. ```typescript const status = await Usercentrics.status(); console.log(`Should collect consent: ${status.shouldCollectConsent}`); console.log(`User location: ${status.location.countryCode}`); console.log(`Number of consents: ${status.consents.length}`); ``` -------------------------------- ### Check Development Environment Requirements Source: https://github.com/usercentrics/react-native-sdk/blob/master/README.md Run this script to verify your development environment meets the SDK's requirements. It helps identify any missing tools or incorrect versions. ```shell npm run check-requirements ``` -------------------------------- ### Configure SDK with Settings ID and Timeout Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/configuration.md Configure the SDK with your settings ID and adjust the initialization timeout. Ensure the settings ID is valid and network connectivity is available. ```typescript Usercentrics.configure({ settingsId: 'YOUR_SETTINGS_ID', loggerLevel: UsercentricsLoggerLevel.debug, // Enable debug logging initTimeoutMillis: 10000 // Increase timeout }); ``` -------------------------------- ### Full Clean and Reinstall Dependencies Source: https://github.com/usercentrics/react-native-sdk/blob/master/sample/README.md Execute these commands for a comprehensive clean and reinstall process, including legacy peer dependencies and iOS pods. ```shell npm run clean-all-caches npm install --legacy-peer-deps npx pod-install # iOS only ``` -------------------------------- ### Basic CMake Configuration Source: https://github.com/usercentrics/react-native-sdk/blob/master/android/src/main/jni/CMakeLists.txt Sets the minimum CMake version and project name. Enables verbose build output. ```cmake cmake_minimum_required(VERSION 3.13) project(rn_usercentrics) set(CMAKE_VERBOSE_MAKEFILE ON) ``` -------------------------------- ### Configure Header Image Settings Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/banner-settings.md Demonstrates creating different header image configurations: extended full-width, sized logo with alignment, and a hidden header. ```typescript import { HeaderImageSettings, BannerLogo, SectionAlignment } from '@usercentrics/react-native-sdk'; import { Image } from 'react-native'; const logoSource = Image.resolveAssetSource(require('./logo.png')); const logo = new BannerLogo('MyLogo', logoSource); // Extended full-width header const extended = HeaderImageSettings.extended(logo); // Sized logo with alignment const sized = HeaderImageSettings.logo(logo, 80, SectionAlignment.center); // Hidden header const hidden = HeaderImageSettings.hidden(); // Use in first layer const firstLayer = new FirstLayerStyleSettings( undefined, sized // headerImage ); ``` -------------------------------- ### Run Unit Tests Source: https://github.com/usercentrics/react-native-sdk/blob/master/sample/README.md Use this script to execute the project's unit tests. ```shell npm test ``` -------------------------------- ### Configure SDK with Version Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/configuration.md Specify the SDK version string. This is typically handled automatically during the build process but can be set manually if needed. ```typescript Usercentrics.configure({ version: '2.27.0' }); ``` -------------------------------- ### Get Complete CMP Data Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/usercentrics.md Retrieves the complete CMP data, including all configured settings, services, categories, language information, and the active variant. ```typescript const cmpData = await Usercentrics.getCMPData(); console.log(`Settings ID: ${cmpData.settings.settingsId}`); console.log(`Available languages: ${cmpData.settings.languagesAvailable}`); console.log(`Number of services: ${cmpData.services.length}`); console.log(`Number of categories: ${cmpData.categories.length}`); console.log(`User location: ${cmpData.userLocation.countryCode}`); ``` -------------------------------- ### Initialize Usercentrics SDK with Options Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/types.md Demonstrates how to create and use a UsercentricsOptions object to configure the SDK. Ensure you replace 'YOUR_SETTINGS_ID' with your actual settings ID. ```typescript const options = new UsercentricsOptions({ settingsId: 'YOUR_SETTINGS_ID', defaultLanguage: 'en', loggerLevel: UsercentricsLoggerLevel.debug, networkMode: NetworkMode.eu }); Usercentrics.configure(options); ``` -------------------------------- ### Fix Metro Port Conflict Source: https://github.com/usercentrics/react-native-sdk/blob/master/sample/README.md A utility command to clear the Metro bundler if it's already running on port 8081, preventing conflicts when starting the app. ```sh npm run fix-metro ``` -------------------------------- ### Example Usage of UsercentricsLocation Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/consent-data.md Demonstrates how to access and use user location data from the SDK status to apply different consent rules and fetch location-specific data. ```typescript import { Usercentrics } from '@usercentrics/react-native-sdk'; const status = await Usercentrics.status(); const location = status.location; console.log(`Country: ${location.countryCode}`); console.log(`Region: ${location.regionCode}`); // Apply different consent rules by location if (location.isInEU) { console.log('GDPR applies'); } else if (location.isInCalifornia) { console.log('CCPA applies'); } else if (location.isInUS) { console.log('State privacy law may apply'); } // Fetch location-specific data const ccpaData = await Usercentrics.getCCPAData(); const gppData = await Usercentrics.getGPPData(); const tcfData = location.isInEU ? await Usercentrics.getTCFData() : null; ``` -------------------------------- ### Get Serialized User Session Data Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/usercentrics.md Returns a serialized string representation of the current user's session data, useful for storage, transfer, or logging. ```typescript const sessionData = await Usercentrics.getUserSessionData(); console.log('User session:', sessionData); ``` -------------------------------- ### Clean and Rebuild Project Source: https://github.com/usercentrics/react-native-sdk/blob/master/sample/README.md Use this script to clean all caches and rebuild the project. ```shell npm run clean-and-build ``` -------------------------------- ### List Available iOS Simulators Source: https://github.com/usercentrics/react-native-sdk/blob/master/sample/README.md List all available iOS simulators that can be targeted when running the React Native application. ```sh xcrun simctl list devices available ``` -------------------------------- ### Initialize Usercentrics SDK Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/README.md Configure the SDK with your settings ID, default language, logger level, and network mode. This should be done early in your application's lifecycle. ```typescript import { Usercentrics, UsercentricsLoggerLevel, NetworkMode } from '@usercentrics/react-native-sdk'; // Configure SDK Usercentrics.configure({ settingsId: 'YOUR_SETTINGS_ID', defaultLanguage: 'en', loggerLevel: UsercentricsLoggerLevel.debug, networkMode: NetworkMode.eu }); // Check consent status const status = await Usercentrics.status(); if (status.shouldCollectConsent) { const response = await Usercentrics.showFirstLayer(); } ``` -------------------------------- ### Get GPP Compliance Data Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/usercentrics.md Retrieves Global Privacy Platform (GPP) data, including the GPP string and applicable sections. Use this for multi-jurisdictional privacy compliance. ```typescript const gppData = await Usercentrics.getGPPData(); console.log(`GPP String: ${gppData.gppString}`); console.log(`Applicable sections: ${gppData.applicableSections.join(', ')}`); ``` -------------------------------- ### Troubleshooting: Clean and Reinstall Dependencies Source: https://github.com/usercentrics/react-native-sdk/blob/master/README.md A troubleshooting step that involves clearing all caches and then reinstalling all project dependencies to resolve potential issues. ```shell npm run clean-all-caches && npm run install-dependencies ``` -------------------------------- ### Get Current Controller ID Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/usercentrics.md Retrieves the current user's unique controller ID. This ID should be stored to restore sessions across app launches or devices. ```typescript const controllerId = await Usercentrics.getControllerId(); await AsyncStorage.setItem('user_controller_id', controllerId); ``` -------------------------------- ### Accessing TCF Features Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/tcf-data.md Demonstrates how to retrieve TCF data and iterate through the features list to log their IDs, names, and descriptions. This example processes all features available in the TCF data. ```typescript const tcfData = await Usercentrics.getTCFData(); tcfData.features.forEach(feature => { console.log(`Feature ${feature.id}: ${feature.name}`); console.log(` Description: ${feature.purposeDescription}`); }); ``` -------------------------------- ### configure Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/usercentrics.md Initializes the Usercentrics SDK with configuration options. This method must be called before any other SDK methods. ```APIDOC ## configure ### Description Initializes the Usercentrics SDK with the provided configuration. This method is synchronous and must be called before any other SDK methods. ### Method configure ### Parameters #### Path Parameters - **options** (UsercentricsOptions) - Required - Configuration object with settings ID, logger level, network mode, and other options ### Request Example ```typescript import { Usercentrics, UsercentricsLoggerLevel, NetworkMode } from '@usercentrics/react-native-sdk'; Usercentrics.configure({ settingsId: 'YOUR_SETTINGS_ID', defaultLanguage: 'en', loggerLevel: UsercentricsLoggerLevel.debug, networkMode: NetworkMode.eu, consentMediation: true }); ``` ``` -------------------------------- ### Handle Network Timeouts Gracefully Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/configuration.md This snippet illustrates how to handle potential SDK initialization timeouts. It uses a try-catch block to log a warning and allows the application to continue with default configurations or a simplified UI. ```typescript try { const status = await Usercentrics.status(); } catch (error) { console.warn('SDK initialization timeout, using defaults:', error); // Continue with cached config or show simplified UI } ``` -------------------------------- ### Run ESLint Source: https://github.com/usercentrics/react-native-sdk/blob/master/sample/README.md Use this script to run ESLint for code linting. ```shell npm run lint ``` -------------------------------- ### Firebase Analytics iOS Setup Source: https://github.com/usercentrics/react-native-sdk/blob/master/sample/README.md Configure Firebase Analytics for iOS by adding the FirebaseAnalytics pod, configuring FirebaseApp, and setting the collection flag in Info.plist. Ensure PrivacyInfo.xcprivacy is updated. ```swift FirebaseApp.configure() // at the top of application(_:didFinishLaunchingWithOptions:) in ios/AppDelegate.swift ``` ```plist FIREBASE_ANALYTICS_COLLECTION_ENABLED set to false in ios/sample/Info.plist ``` -------------------------------- ### Handle Consent Banner Interaction Source: https://github.com/usercentrics/react-native-sdk/blob/master/_autodocs/api-reference/consent-data.md Example of how to process the response from showing the first consent layer. It stores the controller ID and analyzes the user's interaction to log specific events. ```typescript import { Usercentrics, UsercentricsUserInteraction } from '@usercentrics/react-native-sdk'; import AsyncStorage from '@react-native-async-storage/async-storage'; const handleConsentBanner = async () => { const response = await Usercentrics.showFirstLayer(); // Store the controller ID for session restoration await AsyncStorage.setItem('userControlId', response.controllerId); // Analyze user interaction const interactionType = response.userInteraction; if (interactionType === UsercentricsUserInteraction.acceptAll) { console.log('User accepted all consents'); trackEvent('consent_accept_all'); } else if (interactionType === UsercentricsUserInteraction.denyAll) { console.log('User denied all non-essential consents'); trackEvent('consent_deny_all'); } else if (interactionType === UsercentricsUserInteraction.granular) { console.log('User made granular decisions'); // Show which services were accepted vs denied response.consents.forEach(consent => { if (consent.status) { console.log(`✓ ${consent.dataProcessor} accepted`); } else if (!consent.isEssential) { console.log(`✗ ${consent.dataProcessor} denied`); } }); } else if (interactionType === UsercentricsUserInteraction.noInteraction) { console.log('User did not interact with banner'); } }; ```