Module constants (old arch)
info
You may notice, that JS specs contain codegen-related methods, classes, types, etc. to make things more future-proof.
That's because:
- those elements are available since RN older versions (even from v0.65)
- those elements are falling back to "old architecture" implementation (e.g. codegenNativeComponent)
- it introduces type safety for exposed native parts on JS side
- it's much easier to keep single specification on JS side - when old arch will be dropped, there'll be no need to change anything on JS side
So to make it easier, let's use them, to get you more familiar with it 👍
Constants declaration
- JS Spec
- iOS Spec
- Android Spec
src/NativeMyAwesomeModule.ts
import type { TurboModule } from 'react-native';
import { TurboModuleRegistry } from 'react-native';
// ...
export interface Spec extends TurboModule {
getConstants(): { ALONSO: string, HAMILTON: string, LATIFI: string, VERSTAPPEN: string }
}
// TurboModuleRegistry uses NativeModules['MyAwesomeModule'] on old arch
export default TurboModuleRegistry.getEnforcing<Spec>('MyAwesomeModule');
ios/NativeMyAwesomeModule.mm
- (NSDictionary *)getConstants {
return @{
@"ALONSO": @"You always have to leave the space!",
@"HAMILTON": @"Dream the impossible!",
@"LATIFI": @"I don't know what happened there... I'm fine",
@"VERSTAPPEN": @"Don't forget to sanitise!"
};
}
- Kotlin
- Java
android/src/main/newarch/com/myawesomeapp/NativeMyAwesomeModule.kt
override fun getConstants(): MutableMap<String, Any> {
return mutableMapOf(
"ALONSO" to "You always have to leave the space!",
"HAMILTON" to "Dream the impossible!",
"LATIFI" to "I don't know what happened there... I'm fine",
"VERSTAPPEN" to "Don't forget to sanitise!"
)
}
android/src/main/newarch/com/myawesomeapp/NativeMyAwesomeModule.java
import java.util.HashMap;
import java.util.Map;
// ...
@Override
public Map<String, Object> getConstants() {
final Map<String, Object> map = new HashMap<>();
map.put("ALONSO", "You always have to leave the space!");
map.put("HAMILTON", "Dream the impossible!");
map.put("LATIFI", "I don't know what happened there... I'm fine");
map.put("VERSTAPPEN", "Don't forget to sanitise!");
return map;
}