UI Native Module in React Native (P1)

Tram Ho

React Native has provided the basic components used to build your application: view, label, button etc. However, there are times when these components are not enough. This tutorial will introduce how to build a custom UI that can interact between react-native (Javascript) and native (iOS / Android).

The demo uses native libraries, Objective-C, Swift 5, Xcode 11, react-native 0.61 Install require:

  • React Native CLI npm install -g react-native-cli
  • Xcode 11

Create a React-native application

react-native init DemoProject

If using yarn / expo, then after creating, use eject to have 2 ios directories, and corresponding android

react-native run-ios --simulator="iPhone Xs" Test it to make sure the project has been initialized successfully!

Create Native UI Component (iOS)

Open the ios folder

  • run pod install Then open the DemoProject.xcworkspace project

Step 1: Create the Main storyboard file. File → New → Storyboard Step 2: Create the file MyCustomViewController.swift File -> New -> File … -> Swift file

Note: When prompted to create Bridging Header: select Create Bridging Header .

Step 3: Create a file ChangeViewBridge.m / h File -> New -> File … -> Cocoa Touch Class Because React-Native is built to build with ObjectiveC, we need to do a few things to make it work with Swift.

This file will be used later

Step 4: Open the DemoProject-Bridging-Header file Import the libraries from React (related to UIView)

Step 5: Constructing UI and native code Create a ViewController in the Main.storyboard created above

The code in MyCustomViewController file

For demo purposes: The function of the native part is to randomly change the background color of the view. If you need to use frameworks, do the same after importing the framework into the project

Switch views from react-native to native (iOS)

Declare func to enable navigation view to native

Define func in the AppDelegate.m file

Handling the interaction between react-native and native

Now start processing the Objective-C file created earlier

func changeToNativeView will be called from Javascript at react-native

Handling func call from js file

Using NativeModules from react-native, call class ChangeViewBridge and func changeToNativeView () to push view from react-native to native

Refer to the App.js code snippet

Buid app and see the results together


Part 1 also closes here. Part 2 I will guide adding properties, the native callback can communicate with react-natvie. Any questions you can leave a comment, or contact me directly!

See you …

Share the news now

Source : Viblo