Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass data from native android to react native?

I want to pass one string value from native android Main Activity class to react native component. I apply this code, but once I print the "data" in the log it shows undefined. I am not able to understand what is the problem. I am a beginner in react native. Thanks in advance.

In Main Activity:

@Override
    protected ReactActivityDelegate createReactActivityDelegate() {
        return new ReactActivityDelegate(this, getMainComponentName()) {
            @Override
            protected Bundle getLaunchOptions() {

                Bundle initialProperties = new Bundle();
                initialProperties.putString("var_1","Im the first var");
                return initialProperties;
            }
        };
    }

In App.js:

export default class App extends Component<Props> {

  render() {
    var data = this.props.var_1;
    console.log(data);
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>Welcome to React Native!</Text>
        <Text style={styles.welcome}>{this.props.var_1}</Text> 
      </View>
    );
  }
}
like image 242
Silajit Sil Avatar asked Jan 08 '19 09:01

Silajit Sil


Video Answer


2 Answers

There are several ways:

You can send it by emitting event from android activity and handle that event in your react component.

    //Emitting the event from Android Activity.

    public class MainActivity extends ReactActivity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            WritableMap map = Arguments.createMap();
            map.putString("key1", "Value1");
            map.putString("key1", "Value1");

        try {
           getReactInstanceManager().getCurrentReactContext()   
          .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
          .emit("customEventName", map);

            } catch (Exception e){
              Log.e("ReactNative", "Caught Exception: " + e.getMessage());
            }
        }

And in react component addEventListner(subscribe) to that event like as:

import { DeviceEventEmitter } from 'react-native';

componentWillMount: function() {
  DeviceEventEmitter.addListener('customEventName', function(e: Event) {
    // handle event and you will get a value in event object, you can log it here
  });
}

Another way is:

You can store that string in SharedPreferences and can access the same value from the React-native component. Refer below link for the shared preferences use: https://github.com/sriraman/react-native-shared-preferences

like image 169
Bhagwat K Avatar answered Nov 10 '22 05:11

Bhagwat K


The official documentation has several ways to do this.

The one similar to your code using is overriding ReactActivityDelegate.

Make sure you include the relevant imports. I was not using Android Studio and it was not done automatically which caused few errors.

Add these imports to android/app/src/main/java/APPNAME/MainActivity.java:

import com.facebook.react.ReactActivityDelegate;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.Arrays;

Then add the override method to the body of MainActivity class:

  @Override
  protected ReactActivityDelegate createReactActivityDelegate() {
    return new ReactActivityDelegate(this, getMainComponentName()) {
      @Override
      protected Bundle getLaunchOptions() {
        Bundle initialProperties = new Bundle();
        ArrayList<String> imageList = new ArrayList<String>(Arrays.asList(
                "http://example.com/bar1.png",
                "http://example.com/bar2.png"
        ));
        initialProperties.putStringArrayList("images", imageList);
        return initialProperties;
      }
    };
  }

Then in your App.js you can access props.images (images property was added through MainAcitivity. You can name it whatever you want).

This example is using functional component. You can see class based example in the linked documentation.

import React from 'react';
function App(props) {
    console.log('APP PROPS', props.images);
}
like image 37
Kalimah Avatar answered Nov 10 '22 04:11

Kalimah