React Native is developed in such a way that we can create a bridge between the Native Language and the JavaScript code. A bridge is nothing but a way to setup communication between native platform and React Native.
But why do we need it?
Let’s assume you want to reuse some existing Java code or library without having to reimplement it in JavaScript. Yes, you guessed it right, you can use it in your React Native application with the help of Native Bridge. At some point of time, to make a production-level application you will most probably need to use Native Bridge.
“As long as we are building our application purely within the framework, we can drive our app with properties and callbacks. But, when we mix React Native and native components, we need some specific, cross-language mechanisms that would allow us to pass information between them.”
What we will learn in this article?
We will separate this article in two parts which are:
- Native Modules
- Native UI Components
In this article, we are talking about android only.
Native Modules
A Native Module is just a set of javascript functions that are implemented natively for individual platform. Native Modules are used when React Native doesn’t have that required module yet, or when the native performance is significantly better.
To understand this concept better we will implement a toast mechanism in which the toast would be coming from the native android and we will call it from a button made in React Native. In case you are wondering “what a toast is?”, think of it as an alert message for your app.
Let’s start:
Before you start you should have Android Studio and Node.js installed in your computer.
Open your terminal and follow along
npx react-native init ReactNativeBridgeDemo
cd ReactNativeBridgeDemo
Where ReactNativeBridgeDemo is the folder name which will be created.
You will find a folder named ‘android’ in your project. Open that in Android Studio.
From there go to app> java > com.reactnativebridgedemo
Create two files with names ToastModule.java and MyPackage.java. You will understand in a bit why we named that way.
Complete Code with Package you can read here
Top comments (0)