React Native already provides the basic components you would use to build your application: views, labels, buttons, tables, etc.
Note: Most tutorials focus on how to do this in Objective-C, but we'll be using Swift instead.
We will also be using Xcode 10.2 and Android Studio 3.3.2, running in Mac OS 10.14.4
Make sure you have the React Native CLI installed:
Open AwesomeProject/ios/AwesomeProject.xcodeproj in Xcode
Create a new file: File -> New -> File... -> Cocoa Touch Class
Note: When asked, choose Create Bridging Header.
Since React-Native was built with ObjectiveC in mind, we need to do some tricks to be able to make it work with Swift.
First let's create the same file, but in ObjectiveC
And delete the MyCustomView.h since we won't be using it.
Select the file AwesomeProject-Bridging-Header.h and add this content:
Open MyCustomView.swiftand paste the following code to define our view:
Besides this view, we also need an RCTViewManager subclass that will be the one creating and manipulating this view.
Paste this at the bottom of MyCustomView.swift :
Now, the only thing missing is to let ReactNative know about this manager. In order to do this, open MyCustomView.m and replace it's content with the following:
Let's bridge over some native properties. For this we'll create a simple prop and a function.
Open MyCustomView.swift and add the following to your CustomView class:
And replace setupView with the code below:
Now, to make ReactNative aware of these new properties, open MyCustomView.m and replace it with the following:
Import AwesomeProject/android/ into Android Studio
Create a new file: File -> New -> File... and name it MyCustomView.java
Open MyCustomView.java and paste the following code to define our view:
Besides this view, we also need a view manager that will be the one creating and manipulating this view.
Create a file called MyCustomViewManager.java and paste the following :
Now, the only thing missing is to let ReactNative know about this manager. To do this, create a file called MyCustomViewReactPackage.java and paste the following:
In the MainApplication.java file in your project let's add the MyCustomViewReactPackage like this:
Now, let's bridge over some native properties. For this, we'll create the same prop and function like in iOS.
Open MyCustomView.java and add this to your class:
Let's create a simple wrapper for our custom view:
To use it you can do the following:
Once the onClick event is triggered natively it will call the mapped prop to switch the status props coming into the MyCustomView.
The full source code for this project is available in https://github.com/calitb/RN-NativeViews