Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing string from native module to react native

Tags:

react-native

I create a native module for android (in kotlin language)

class TestModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
    override fun getName(): String {
        return "TestModule"
    }

    @ReactMethod
    fun testing(): String{
        return "my modules"
    }

}

I then registered this module in the ModulesPackages and add it to MainApplication.tk as instructed at https://facebook.github.io/react-native/docs/native-modules-android.html

in App.js

import {NativeModules} from 'react-native'
const TestingModule = NativeModules.TestModule;
type Props = {};
export default class App extends Component<Props> {
  render() {

    alert(TestingModule.testing());

    return (
      <View style={styles.container}>
        <Text style={styles.instructions}> test</Text>
      </View>

    );
  }
}

After running this, I expect to get the alert with the text "my modules", but I got alert with text "undefined"

I can't figure out what I did wrong. I did not see any error or complain when I run react-native run-android.

Any suggestion what I did wrong?

like image 339
Denvi Avatar asked Oct 23 '25 16:10

Denvi


1 Answers

To make communication between native module and js module, you should invoke callback, promise or use event. In your case, the testing function could be change like

import com.facebook.react.bridge.Callback;

...

@ReactMethod
fun testing(callback: Callback): Void{
    callback.invoke("my modules")
}

Edit

you should pass a callback in js file in this case:

testCallback = (name) => {
    console.log(name);
}

componentDidMount() {
    TestingModule.testing(this.testCallback);
}
like image 184
tuan.tran Avatar answered Oct 26 '25 12:10

tuan.tran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!