cagin
cagin

Reputation: 5930

How to pass parameter to swift class from react native bridge

I have a react native app and I call a swift class from this app. I use a bridge for that and I want to pass a parameter to init of my Counter class. How can I do that? I am very new on swift and react.

@interface RCT_EXTERN_MODULE(Counter, NSObject)

swift version is 5.0 react native version is 0.62.1

Upvotes: 2

Views: 3848

Answers (1)

iUrii
iUrii

Reputation: 13818

You can't pass params from js to instantiate your native module since RN creates singleton instances for every bridge with default initializer init. But you can set needed properties with a function e.g.

MyModuleExport.m:

@interface RCT_EXTERN_MODULE(MyModule, NSObject)

RCT_EXTERN_METHOD(construct:(NSString*)name value:(NSInteger)value)

@end

MyModule.swift:

@objc(MyModule)    
class MyModule: NSObject {
    var name: String!
    var value: Int!

    @objc
    func construct(_ name: String, value: Int) {
        self.name = name
        self.value = value
    }

JS:

const module = NativeModules.MyModule
module.construct("Hello", 100);

Upvotes: 3

Related Questions