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
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.
This file is located in android/app/src/main/java/com/<yourproject>/MainActivity. java .
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 .
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);
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;
}
};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With