Export data from React Native to Native

I have a number of components that are being integrated into Android and iOS apps, and would like to have some metadata that lives alongside the React Native code that gives the apps some information about the components before they are mounted/loaded.

The native React Native framework allows one to inject constants and functions through "native modules," which can be accessed globally without being tied to a component, activity, view controller, etc. Basically, we can easily send data Native => React Native.

Is there a simple way to do the same thing from React Native => Native, like exposing a constant or a function which can be accessed through the React bridge/context by the native app?

I needed to pass some data from React Native to Native(iOS) for that I have used Notifications. May be this can help some one.

Import NativeModules in your React Native file

import {
  StyleSheet,
  AppRegistry,
  Text,
  TextInput,
  View,
  NavigatorIOS,
  Button,
  ActivityIndicator,
  TouchableHighlight,
  FlatList,
  NativeModules
} from 'react-native';

const NotificationsModule = NativeModules.NotificationsModule;

Then add notification when needed

Create your dictionary of data you want to send

const params = { "yourKey": "value"};

NotificationsModule.sendNotification("OrderLoaded", yourParams);
Then go in your xcode and add create NotificationsModule file

Your NotificationsModule.h file

#import <Foundation/Foundation.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>

@interface NotificationsModule : NSObject

@end

Your NotificationsModule.m file

#import <React/RCTConvert.h>
#import <React/RCTLog.h>
#import <React/RCTBridgeModule.h>
@interface NotificationsModule : NSObject<RCTBridgeModule>
@end

@implementation NotificationsModule

RCT_EXPORT_MODULE();
RCT_EXPORT_METHOD(sendNotification:(NSString*)notification params:(NSDictionary*)params) {
    if ([notification isCaseInsensitiveEqualToString:@"OrderLoaded"]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"OrderLoaded" object:nil userInfo:params];
    }
}


@end

And observe the change via adding below line in your controller where you wants to know the change

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(OrderLoaded:) name:@"OrderLoaded" object:nil];

And finally your method

- (void)OrderLoaded:(NSNotification*)notification
{
    NSMutableDictionary *dictionary = [notification.userInfo mutableCopy];

    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        NSString *yourData = [dictionary valueForKey:@"yourKey"];
        // Do your stuff with yourData           
    });
}

Comments

Popular posts from this blog

Meaning of `{}` for return expression

Get current scroll position of ScrollView in React Native

React Native - Image Cache