Create Library
In order to create the react native module project, use the install react-native-create-library command:
npm install -g react-native-create-library
And then create your module:
react-native-create-library -—platforms ios,android NativeToastLibrary
Android
Update file 'build.gradle'
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.0.4'
}
}
apply plugin: 'com.android.library'
android {
...
}
repositories {
google()
mavenCentral()
maven {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
url "$rootDir/../node_modules/react-native/android"
}
}
dependencies {
api 'com.facebook.react:react-native:+'
}
Update file RNNativeToastLibraryModule.java
public class RNNativeToastLibraryModule extends ReactContextBaseJavaModule {
public RNNativeToastLibraryModule(ReactApplicationContext reactContext) {
super(reactContext);
}
/**
* Show toast.
* @param text to display
* @param promise [optional]: then(...).catch(...)
*/
@ReactMethod
public void show(String text, Promise promise) {
if (TextUtils.isEmpty(text)) {
promise.reject(new Exception("text is empty"));
} else {
Toast.makeText(getReactApplicationContext(), text, Toast.LENGTH_LONG).show();
promise.resolve(text);
}
}
/**
* Name of the module with which we will do from javascript
*/
@Override
public String getName() {
return "RNNativeToastLibrary";
}
}
iOS
Open RNNativeToastLibrary.xcodeproj
in Xcode.
You should have an error that Xcode doesn’t recognise RCTBridgeModule.h
(if not, continue to the next step). In order to fix this issue, open the file package.json
in the project directory and above the peerDependencies
line add:
"devDependencies": {
"react-native": "0.41.2"
},
"peerDependencies": {
"react": "*",
"react-native": "0.41.2"
}
Now open the terminal, get into the project directory and type npm install
.
When you look at the project directory again, you should see that a node_modules
directory was added.
1. Add a React Native iOS Project
Open the RNNativeToastLibrary (1) and select the Build Phases (2) tab. Click Link Binary with Libraries (3) and then click on the plus button (4).
In the popup window click the Add Other… button
, and choose node_modules
> react-native
> React
> React.xcodeproj
:
2. Add a React Native iOS Library
Open the RNNativeToastLibrary (1) project on the top (with the blue icon) and select the Build Phases (2) tab. Click Link Binary with Libraries (3) and then click on the plus button (4)
In the popup window choose libReact.a
from React target
Build your project (Command + B)
. You should see that RCTBridgeModule.h
is recognised.
RNNativeToastLibrary.m
Update file #import "RNNativeToastLibrary.h"
#import "IOSNativeToast.h"
// Interface:
@interface RNNativeToastLibrary()
// Propiedades:
@property (nonatomic, retain) IOSNativeToast *toast;
@end
// Funciones:
@implementation RNNativeToastLibrary
/**
Inicialización del objeto:
*/
- (instancetype)init {
self = [super init];
if (self) {
// inicialíza el toast
self.toast = [[IOSNativeToast alloc] init];
}
return self;
}
/**
Debido a que anulamos el método init, también debemos
implementar requireMainQueueSetup (si queremos que se ejecute
en el subproceso principal).
*/
+ (BOOL)requiresMainQueueSetup
{
return YES;
}
/**/
- (dispatch_queue_t)methodQueue
{
return dispatch_get_main_queue();
}
RCT_EXPORT_MODULE()
/*
@param text texto a mostrar
@param resolver [opcional] promesa: then(...)
@param rejecter [opcional] promesa: catch(...)
*/
RCT_EXPORT_METHOD(show:
(NSString *)text
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject
) {
if ([text length] == 0) {
NSError *err = nil;
reject(@"no_data", @"Text is empty.", err);
} else {
resolve(text);
[self.toast showToast:text];
}
}
@end
Upload your library to NPM
Move to the public npm using the command
npm config set registry https://registry.npmjs.org/
Open the terminal in the project directory, and type npm adduser
and then
your username details.
Lastly, type npm publish
to publish your code.
We get the url of the dependency
$ npm view react-native-toast-library-32 dist.tarball
Create Podspec IOS
react-native-toast-library-32.podspec
Create file require 'json'
package = JSON.parse(File.read(File.join(__dir__, 'package.json')))
Pod::Spec.new do |s|
s.name = package['name']
s.version = package['version']
s.summary = package['description']
s.description = package['description']
s.license = package['license']
s.author = package['author']
s.homepage = package['homepage']
s.source = {
#:git => 'https://github.com/jbmx/react-native-toast-library-32.git'
:http => 'https://registry.npmjs.org/react-native-toast-library-32/-/react-native-toast-library-32-1.0.7.tgz'
}
s.requires_arc = true
s.platform = :ios, '7.0'
s.preserve_paths = 'README.md', 'package.json', 'index.js'
s.source_files = 'ios/*.{h,m}'
s.dependency 'React'
end
Install react-native-toast-library-32
Getting started
$ npm install react-native-toast-library-32
iOS
$ cd ios & pod install
Usage
import RNNativeToastLibrary from 'react-native-toast-library-32';
// TODO: What to do with the module?
RNNativeToastLibrary.show("Hola mundo");