Native Modules
Native modules let us access native APIs through JavaScript. All of the built-in components, like View
and Image
, are native modules. There are also non-component native modules, like the Animated
module.
Bridging APIs
When writing a native module to expose native APIs, we call this bridging an API. The process for bridging components and non-component APIs is somewhat different, but the main idea is the same: we need to register a native Swift/Kotlin function to handle each JavaScript function call. React Native includes classes/methods/macros for registering these functions from native code.
In this guide we'll briefly cover the steps involved in bridging a component.
Bridging an API is fairly formulaic, but may be difficult if you don't have native development experience.
Bridging a component
How to expose a native UI component to JavaScript:
- Create a native UIView or Android View subclass
- Create a React ViewManager subclass that manages a pool of the view subclass
- Register the ViewManager subclass with React Native
requireNativeComponent
from JS
These steps are essentially the same for iOS and Android.
Tip: be careful with names! The names of the annotations do matter. Replace "My" in the examples with the component name you want.
1. Create a native view subclass
This can be any view - there's nothing specific to React Native yet.
2. Create a ViewManager subclass
A ViewManager manages a pool of our View subclass from the previous step. Native views are reused as much as possible for better performance.
3. Register the ViewManager subclass
We need to let React Native know about our ViewManager by registering it.
4. Load the native module from JS
Once we've registered a ViewManager on the native side, we can instantiate the view as a React component.
5. Props
Next, we need to pass props from JS to native:
Also...
Since React Native projects are in Obj-C & Java:
- Let Android Studio enable Kotlin
- Let Xcode add a bridging header
Want to learn React Native in-depth?
If you like React Native Express, you'll love my new book, Fullstack React Native: The complete guide to React Native! Throughout the book, we'll build 7 full apps, covering complex topics like navigation, gestures, and native modules. We don't assume any knowledge of React or newer JavaScript language features, so you can dive right in regardless of your experience level. The book comes in PDF
, EPUB
and MOBI
formats.
Community Resources
Looking for more help?
Infinite Red sponsors React Native Express and is the premier React Native agency. They're also the team behind the React Native newsletter, podcast, and conference listed here. Get in touch at infinite.red/react-native for a proposal on your next project!