Create a custom React Native module that exports Constants (with Swift)

In this post, we will create a simple React Native module using Swift. The module will return information about the current device and expose it to JavaScript.

First, we create our Swift class, RNDevice.swift.

This class will is responsible for returning information that describes the current device. This information is obtain using the UIDevice class.

import UIKit

@objc(RNDevice)
class RNDevice: NSObject {
  
  @objc func constantsToExport() -> NSObject {
    let currentDevice = UIDevice.currentDevice()
    return [
      "name": currentDevice.name,
      "systemName": currentDevice.systemName,
      "systemVersion": currentDevice.systemVersion,
      "localizedModel":currentDevice.localizedModel,
      "model": currentDevice.model
    ]
  }
}

Next, we create the bridge to React Native and externalize the RNDevice class (above), so that it can be called by name from JavaScript

#import "RCTBridgeModule.h"

@interface RCT_EXTERN_MODULE(RNDevice, NSObject)

@end

Finally, to obtain the device properties from JavaScript, we can invoke the new RNDevice module using the following code:

const { RNDevice } = require('NativeModules');
console.log(RNDevice);

You may also like...

Leave a Reply