Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native - initialProperties Android

I'm working under React-Native and I'm looking for passing initial props to JS via Java. This can be done easily in Objective-C with initialProperties like this :

RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"myapp"
                                               initialProperties:initialProperties
                                                   launchOptions:launchOptions];

Where initialProperties is an NSDictionary which will be converted in JSON and available in JS via this.props. So I'm looking to do the same in Android. Any help ? Thanks

like image 866
ilansas Avatar asked Dec 02 '15 16:12

ilansas


People also ask

How do I send data from Android to React Native?

You can pass a callback as a function in your client (js) code and invoke it in the Java module with the data you want to return. You need to import the Callback bridge module in your Java class: import com.

Where is MainActivity Java in React Native?

This file is located in android/app/src/main/java/com/<yourproject>/MainActivity. java .

How do you call native Android code in React Native?

In order to access your native module from JavaScript you need to first import NativeModules from React Native: import { NativeModules } from 'react-native'; You can then access the CalendarModule native module off of NativeModules .


2 Answers

In Android, you can pass initialProps in with the launchOptions as a Bundle.

As is mentioned here in the source code: https://github.com/facebook/react-native/blob/7377fdcc70b25eb023e7c6d1b37eeae2a700cb88/ReactAndroid/src/main/java/com/facebook/react/ReactRootView.java#L325-L334

So you can do something like this:

Bundle initialProps = new Bundle();
initialProps.putString("myKey", "myValue");

mReactRootView.startReactApplication(mReactInstanceManager, "MyAwesomeApp", initialProps);
like image 151
Dave Sibiski Avatar answered Sep 27 '22 22:09

Dave Sibiski


getlauchOptions has been moved inside ReactActivityDelegate, now I use this code:

public class MainActivity extends ReactActivity {

/**
 * Returns the name of the main component registered from JavaScript.
 * This is used to schedule rendering of the component.
 */
@Override
protected String getMainComponentName() {
    return "myAppName";
}

@Override
protected ReactActivityDelegate createReactActivityDelegate() {
    return new ReactActivityDelegate(this, getMainComponentName()) {
        @Nullable
        @Override
        protected Bundle getLaunchOptions() {
            Bundle initialProps = new Bundle();
            initialProps.putString("SOME_VARIABLE_1", BuildConfig.SOME_VARIABLE_1);
            initialProps.putString("SOME_VARIABLE_2", "some variable 2 value");
            return initialProps;
        }
    };
}
like image 23
Michele Avatar answered Sep 27 '22 22:09

Michele