Introduction
Integrating React Native right into a native software, both Android or iOS, might be complicated if not achieved accurately. On this article, our purpose is to combine React Native elements right into a native Android software.
One of many largest advantages of integrating React Native when creating cell purposes is the flexibility to reuse code throughout each iOS and Android apps. This offers virtually full code reusability after React Native has been built-in into an current software, lowering improvement time and improvement price significantly.
We’ll cowl the next:
Stipulations
- A React Native improvement setting (React Native CLI); comply with this hyperlink for directions on the way to rise up and operating with the React Native CLI
- Android improvement setting (Android Studio)
Getting began with our React Native challenge
First, let’s initialize our React Native challenge.
npx react-native init nativeandroid cd nativeandroid
Begin up the Metro Bundler and run the next command inside our React Native challenge folder:
npx react-native begin
Now, begin the applying.
npx react-native run-android
If setup has been accomplished accurately, the Android software ought to begin on the Android Studio emulator.
Organising challenge directories
If no native Android software has been created utilizing Android Studio, a brand new software might be created.
Utilizing Android Studio, a primary fragment Android cell software has been created.
Â
Organising the file integration listing
This listing will maintain our React Native software and Native Android software. Create an Android folder:
mkdir ReactNativeIntegration cd ReactNativeIntegration mkdir android
Navigate to the foundation folder of the Android software created with Android Studio, copy all of the recordsdata from the Android software within the AndroidStudioProjects
file, and paste it into the Android folder that we simply created.
Create a package deal.json
within the ReactNativeIntegration
folder.
cd .. contact package deal.json code package deal.json
Add the code block under to the empty package deal.json
file.
{ "identify": "nativeandroid", "model": "0.0.1", "non-public": true, "scripts": { "begin": "npx react-native begin", "android": "npx react-native run-android" } }
On the finish, the file listing ought to seem like this:
Set up dependencies
Right here, we set up:
[email protected]
- React – the JavaScript library for constructing consumer interfaces
hermesvsm
– JavaScript for operating our React Native softwarejsc-android
– Maintainable construct script permitting React Native to include up-to-date releases of JSC into the framework
yarn add [email protected] react hermesvm jsc-android @react-native-community/[email protected]
Configuring Maven
Maven is the go-to instrument for managing and constructing our challenge. It’s useful, because it routinely fetches dependencies primarily based on the wants of the challenge, dealing with transitive dependencies as effectively.
To begin, open Android Studio within the native software’s construct.gradle
file.
Add these strains of code to the dependencies part:
dependencies { //noinspection GradleCompatible implementation "com.android.assist:appcompat-v7:27.1.1" implementation "com.fb.react:react-native:+" // From node_modules implementation "org.webkit:android-jsc:+" }
We’ll reap the benefits of the facility of autolinking to allow our software to entry native modules and use native modules supplied by React Native libraries. Add the road of code to the underside of the construct.gradle
file, under the dependencies part.
apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(challenge)
Navigate to the construct.gradle
file in our androidApplication
file.
Add the code under on the high stage of the construct.gradle
file:
allprojects { repositories { maven { // All of React Native (JS, Android binaries) is put in from npm url ("$rootDir/../node_modules/react-native/android") } maven { // Android JSC is put in from npm url("$rootDir/../node_modules/jsc-android/dist") } google() jcenter() } } process clear(kind: Delete) { delete rootProject.buildDir }
In settings.gradle
, add the road of code on the backside to allow autolinking.
apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
Remark out the dependencyResolutionManagement
code block.
pluginManagement { repositories { gradlePluginPortal() google() mavenCentral() } } //dependencyResolutionManagement { // repositorMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) // repositories { // google() // mavenCentral() // } //}
Sync the Gradle modifications. There needs to be no errors.
Permitting permission to entry the web
Web permissions might be enabled within the AndroidManifest.xml
file by including the next code to the AndroidManifest.xml
file.
<uses-permission android:identify="android.permission.INTERNET" />
<?xml model="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package deal="com.instance.androidapplication"> <uses-permission android:identify="android.permission.INTERNET" />
DevSettings entry permissions must also be enabled.
Then, add the next code to the AndroidManifest.xml
file:
<exercise android:identify="com.fb.react.devsupport.DevSettingsActivity" />
</intent-filter> </exercise> <exercise android:identify="com.fb.react.devsupport.DevSettingsActivity" /> </software>
When creating manufacturing launch builds, it’s suggested to strip the dev settings permission, as it’s only wanted when reloading JavaScript from the event server.
Enabling cleartext in debug builds
On account of some modifications launched in Android 9 (API stage 28), cleartext site visitors is disabled by default. Our software is unable to connect with Metro Bundler in consequence.
Within the AndroidManifest.xml
file, add the useCleartextTraffic
choice to the debug.
<software android:usesCleartextTraffic="true"> </software>
When creating launch builds, this isn’t obligatory.
To spherical up the combination course of, the native Android software code shall be modified to combine React Native.
Integrating React Native code into the native Android app
Within the root of our React Native Combine
folder, create an index.js
file.
contact index.js
Enter the code block under into the index.js
file:
import React from "react"; import { AppRegistry, StyleSheet, Textual content, View } from "react-native"; const Integration = () => { return ( <View model={types.container}> <Textual content model={types.howdy}>Whats up, World</Textual content> </View> ); }; var types = StyleSheet.create({ container: { flex: 1, justifyContent: "heart", }, howdy: { fontSize: 20, textAlign: "heart", margin: 10, }, }); AppRegistry.registerComponent("IntegratedApp", () => Integration);
Writing native code
With a view to begin the React Native runtime and inform it to render our JS element, we should create a file referred to as ReactActivity
in Android Studio.
Opening up the Android challenge in Android Studio, create a category referred to as ReactActivity
that extends Exercise and creates a ReactRootView
, which begins a React software and units it because the
Add the code block under to the ReactActivity.java
file.
package deal com.instance.androidapplication; import android.app.Exercise; import android.os.Bundle; import com.fb.react.PackageList; import com.fb.react.ReactInstanceManager; import com.fb.react.ReactPackage; import com.fb.react.ReactRootView; import com.fb.react.widespread.LifecycleState; import com.fb.react.modules.core.DefaultHardwareBackBtnHandler; import com.fb.soloader.SoLoader; import java.util.Checklist; public class MyReactActivity extends Exercise implements DefaultHardwareBackBtnHandler { non-public ReactRootView mReactRootView; non-public ReactInstanceManager mReactInstanceManager; @Override protected void onCreate(Bundle savedInstanceState) { tremendous.onCreate(savedInstanceState); SoLoader.init(this, false); mReactRootView = new ReactRootView(this); Checklist<ReactPackage> packages = new PackageList(getApplication()).getPackages(); // Packages that can not be autolinked but might be added manually right here, for instance: // packages.add(new MyReactNativePackage()); // Bear in mind to incorporate them in `settings.gradle` and `app/construct.gradle` too. mReactInstanceManager = ReactInstanceManager.builder() .setApplication(getApplication()) .setCurrentActivity(this) .setBundleAssetName("index.android.bundle") .setJSMainModulePath("index") .addPackages(packages) .setUseDeveloperSupport(BuildConfig.DEBUG) .setInitialLifecycleState(LifecycleState.RESUMED) .construct(); // The string right here (e.g. "IntegratedApp") has to match // the string in AppRegistry.registerComponent() in index.js mReactRootView.startReactApplication(mReactInstanceManager, "IntegratedApp", null); setContentView(mReactRootView); } @Override public void invokeDefaultOnBackPressed() { tremendous.onBackPressed(); } }
Now, begin the applying.
npm run begin
Conclusion
Integrating React Native elements might be fairly a process, however the improvement advantages outweigh the challenges. With React Native being an open supply framework, builders acquire entry to an enormous array of shared codebases after integrating their purposes with React Native, which improves the developer expertise and aids in speedier software improvement.
I hope this text has supplied you with a enough information.
LogRocket: Immediately recreate points in your React Native apps.
LogRocket is a React Native monitoring answer that helps you reproduce points immediately, prioritize bugs, and perceive efficiency in your React Native apps.
LogRocket additionally helps you improve conversion charges and product utilization by exhibiting you precisely how customers are interacting along with your app. LogRocket’s product analytics options floor the explanation why customers do not full a selected stream or do not undertake a brand new function.
Begin proactively monitoring your React Native apps — attempt LogRocket without spending a dime.