Updated 5 March 2021
In this blog, we will learn about passing Information from Java to JavaScript in our React Native Application.
Well, react native has a huge community and makes everything easy especially for cross-platform developments (both Android & iOS).
As a result, most of the problems a beginner developer will face have already been posted and resolved over the internet.
But sometimes we just want to do a few things in the Android Code and then pass on this to the javascript.
Let’s see how we can do this
First, we will just have a look at the Android Side Changes
Let’s just say I want to Transfer a String to javascript code from our MainActivity.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
public class MainActivity extends ReactActivity { public String stringFromJava = "This string is coming from Java Code"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); WritableMap payload = Arguments.createMap(); // Put data to map payload.putString("MyCustomEventParam", stringFromJava); // Emitting event from java code (getReactNativeHost().getReactInstanceManager().getCurrentReactContext()).getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit("MyCustomEvent", payload); } /** * Returns the name of the main component registered from JavaScript. * This is used to schedule rendering of the component. */ @Override protected String getMainComponentName() { return "DemoApplication"; } } |
With this, you are able to emit an event from your native java to javascript.
But Still, you will not be able to receive this event in your javascript code as you have not subscribed to this event.
So, now let’s just have a look at the javascript side changes you need to make.
Let’s say I want to receive this event in my App.js file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import React, { Component } from "react"; import { View, Text, DeviceEventEmitter // other react-native components that you want to import } from "react-native"; // your other import statements export default class App extends Component { componentDidMount() { DeviceEventEmitter.addListener('MyCustomEvent',(event)=>{ console.log("MyCustomEvent -->",event); console.log("MyCustomEvent MyCustomEventParam -->", event.MyCustomEventParam); // Add your Business Logic over here }); } render() { return ( <View> <Text> Sample Demo App for Recieving information from Java to Java Script</Text> </View> ); } } |
Hope this helps you.
Keep coding and Keep Sharing 🙂
References : 1) https://facebook.github.io/react-native/docs/native-components-android#events
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.