Skip to content

SurveyMonkey/surveymonkey-react-native

Repository files navigation

SurveyMonkey for React Native

React Native bridge for the native SurveyMonkey Mobile Feedback SDK (iOS & Android).

Features

  • New Architecture - Full Turbo Module support (RN 0.71+)
  • SwiftUI Compatible - Works seamlessly with SwiftUI apps
  • Modern Kotlin - Android implementation in Kotlin 1.9.22
  • iOS 13+ - Scene-based architecture, multi-window iPad support
  • Backward Compatible - Tested on RN 0.61.5 through 0.74.5
  • Type-Safe - Full TypeScript definitions

Requirements

  • React Native: 0.61.5 - 0.74.5 (0.73+ recommended for New Architecture)
  • iOS: iOS 13.0+, Swift 5.5+, Xcode 16+
  • Android: API 21+, Java 17+, Gradle 8.0+
  • SurveyMonkey Mobile SDK Collector account

Installation

npm install surveymonkey-react-native
# or
yarn add surveymonkey-react-native

iOS Setup

cd ios && pod install && cd ..

That's it! No additional configuration needed. The SDK auto-initializes when your app loads.

Note: Ensure your ios/Podfile has platform :ios, '13.0' or higher.

Android Setup

No configuration required! The SDK auto-initializes when your app loads.

Just ensure your project meets the minimum requirements:

  • Java 17+ (check with java -version)
  • compileSdkVersion 34+ in android/build.gradle
📋 Verify Android Configuration (optional)

Ensure android/build.gradle has:

buildscript {
    ext {
        compileSdkVersion = 34
        targetSdkVersion = 34
    }
    dependencies {
        classpath("com.android.tools.build:gradle:8.1.4")
    }
}

Quick Start

import SurveyMonkey from 'surveymonkey-react-native';

// Present a survey
SurveyMonkey.presentSurvey('YOUR_SURVEY_HASH');

Example App

# From root directory
npm run example:ios       # Run on iOS
npm run example:android   # Run on Android
npm run example:clean     # Clean build artifacts

# Or from example directory
cd example
npm run ios      # Run on iOS
npm run android  # Run on Android
npm run clean    # Clean build artifacts

See example/README.md for full documentation and example/TESTING.md for multi-version testing instructions.

Usage

Basic Integration

Import the library in your React Native component:

import React, { useEffect } from 'react';
import { Button, Alert } from 'react-native';
import SurveyMonkey from 'surveymonkey-react-native';

Present a Survey

Present a survey directly to the user using the collector hash from your SurveyMonkey Mobile SDK Collector:

const MyComponent = () => {
    const showSurvey = () => {
        // Basic survey
        SurveyMonkey.presentSurvey('YOUR_SURVEY_HASH');
    };

    const showSurveyWithData = () => {
        // With custom variables (Advantage plan+ only)
        SurveyMonkey.presentSurvey('YOUR_SURVEY_HASH', {
            user_id: '12345',
            email: 'user@example.com',
            plan: 'premium',
        });
    };

    return (
        <>
            <Button title="Show Survey" onPress={showSurvey} />
            <Button title="Show Survey with Custom Data" onPress={showSurveyWithData} />
        </>
    );
};

Listen for Survey Events

Set up event listeners to handle survey completion, errors, and other events:

const MyComponent = () => {
    useEffect(() => {
        // Listen for survey completion
        const completeListener = SurveyMonkey.onSurveyComplete((event) => {
            if (event.respondent) {
                console.log('✅ Survey completed!');
                console.log('Responses:', event.respondent.questionResponses);
                
                // Process responses
                event.respondent.questionResponses.forEach((question) => {
                    console.log(`Question ${question.questionID}:`);
                    question.answers.forEach((answer) => {
                        console.log(`  - ${answer.text || answer.rowID}`);
                    });
                });
            } else if (event.error) {
                console.log('❌ Survey error:', event.error);
            }
        });

        // Listen for survey errors
        const errorListener = SurveyMonkey.onSurveyError((event) => {
            console.error('Failed to load survey:', event.error);
            Alert.alert('Survey Error', event.error);
        });

        // Listen for when survey is presented
        const presentedListener = SurveyMonkey.onSurveyPresented(() => {
            console.log('Survey is now visible');
        });

        // Listen for when survey is dismissed
        const dismissedListener = SurveyMonkey.onSurveyDismissed((event) => {
            console.log('Survey was dismissed');
        });

        // Cleanup listeners when component unmounts
        return () => {
            completeListener.remove();
            errorListener.remove();
            presentedListener.remove();
            dismissedListener.remove();
        };
    }, []);

    return (
        <Button 
            title="Take Survey" 
            onPress={() => SurveyMonkey.presentSurvey('YOUR_SURVEY_HASH')} 
        />
    );
};

Schedule an Intercept

Use the intercept feature to prompt users to take your survey at timed intervals (e.g., 3 days after install):

const MyComponent = () => {
    useEffect(() => {
        // Schedule intercept with default intervals
        // (3 days after install, 3 weeks after decline, 3 months after accept)
        SurveyMonkey.scheduleIntercept('YOUR_SURVEY_HASH', 'My App');

        // Or with custom options
        SurveyMonkey.scheduleIntercept('YOUR_SURVEY_HASH', 'My App', {
            alertTitle: "We'd love your feedback!",
            alertBody: 'Would you like to take a quick survey?',
            positiveActionTitle: 'Sure!',
            cancelTitle: 'No Thanks',
            afterInstallInterval: 86400000,   // 1 day in milliseconds
            afterAcceptInterval: 2592000000,  // 30 days in milliseconds
            afterDeclineInterval: 604800000,  // 7 days in milliseconds
        });
    }, []);

    return null; // Intercept runs automatically based on intervals
};

Customize Appearance (iOS Only)

// Set the cancel/close button tint color
SurveyMonkey.setCancelButtonTintColor('#FF6600');

Complete Example

Here's a complete component showing all features:

import React, { useEffect, useState } from 'react';
import { View, Button, Text, StyleSheet, Alert } from 'react-native';
import SurveyMonkey from 'surveymonkey-react-native';

const SURVEY_HASH = 'YOUR_SURVEY_HASH_HERE';

const SurveyScreen = () => {
    const [surveyCompleted, setSurveyCompleted] = useState(false);

    useEffect(() => {
        // Set iOS cancel button color
        SurveyMonkey.setCancelButtonTintColor('#FF6600');

        // Set up event listeners
        const completeListener = SurveyMonkey.onSurveyComplete((event) => {
            if (event.respondent) {
                setSurveyCompleted(true);
                Alert.alert('Thank You!', 'Survey completed successfully');
            } else if (event.error) {
                Alert.alert('Error', event.error);
            }
        });

        const errorListener = SurveyMonkey.onSurveyError((event) => {
            Alert.alert('Survey Error', event.error);
        });

        // Schedule intercept on component mount
        SurveyMonkey.scheduleIntercept(SURVEY_HASH, 'My App');

        return () => {
            completeListener.remove();
            errorListener.remove();
        };
    }, []);

    return (
        <View style={styles.container}>
            <Text style={styles.title}>
                {surveyCompleted ? '✓ Survey Completed' : 'Help us improve!'}
            </Text>
            
            <Button
                title="Take Survey"
                onPress={() => SurveyMonkey.presentSurvey(SURVEY_HASH)}
            />
            
            <Button
                title="Survey with User Data"
                onPress={() => SurveyMonkey.presentSurvey(SURVEY_HASH, {
                    user_id: '12345',
                    email: 'user@example.com',
                })}
                color="#2196F3"
            />
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        padding: 20,
    },
    title: {
        fontSize: 20,
        marginBottom: 20,
        textAlign: 'center',
    },
});

export default SurveyScreen;

API Reference

Method Platforms Description
presentSurvey(hash, customVars?) iOS, Android Present survey immediately
scheduleIntercept(hash, appTitle, options?) iOS, Android Schedule timed intercept
setCancelButtonTintColor(hex) iOS Set cancel button color
onSurveyComplete(callback) iOS, Android Survey completion event
onSurveyError(callback) iOS, Android Survey error event
onSurveyPresented(callback) iOS, Android Survey presented event
onSurveyDismissed(callback) iOS, Android Survey dismissed event
removeAllListeners() iOS, Android Remove all listeners

Getting Your Survey Hash

  1. Log in to SurveyMonkey
  2. Create or select a survey
  3. Go to Collect ResponsesMobile SDK
  4. Generate your Survey Hash
  5. Use it in presentSurvey() or scheduleIntercept()

TypeScript

Full TypeScript definitions included:

import SurveyMonkey, { 
    SurveyCompleteEvent,
    InterceptOptions 
} from 'surveymonkey-react-native';

const handleComplete = (event: SurveyCompleteEvent) => {
    console.log(event.respondent?.questionResponses);
};

SurveyMonkey.onSurveyComplete(handleComplete);

License

MIT

Support

About

The SurveyMonkey Mobile Feedback SDK for React Native

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors