NativeScript with React Native Modules
The React Native community is a rich ecosystem of diverse native platform modules which you can use with NativeScript projects.
When it comes to platform versatility in development options, NativeScript packs a punch with extensive interop power. Let's look at using React Native Modules across Angular, React, Solid, Svelte and Vue on iOS and Android.
React Native with Angular
React Native with React
👉 Well yes this works 😄
React Native with Solid
👉 https://stackblitz.com/edit/nativescript-react-native-modules-solid?file=app%2Fapp.jsx
React Native with Svelte
React Native with Vue
👉 Vue 3: https://stackblitz.com/edit/nativescript-react-native-modules-vue3?file=src%2Fcomponents%2FHome.vue
Open Native
Open Native brings cross-platform communities together to help them collaborate and strengthen each other through development diversity.
For example, we can use React Native Modules with NativeScript by taking advantage of Open Native.
Install with React Native Modules
npm install @open-native/core
We can now install React Native Modules, for example:
npm install @react-native-community/netinfo
npm install react-native-device-info
We will now want to configure out app to use them.
Configure
Configuring webpack is the first thing we'll want to do. In order to import React Native Modules throughout our project, we'll need babel so we can install:
npm install metro-react-native-babel-preset -D
Now we can configure our webpack.config.js to use them:
const webpack = require('@nativescript/webpack');
const { join } = require('path');
module.exports = (env) => {
webpack.init(env);
// Learn how to customize:
// https://docs.nativescript.org/webpack
webpack.chainWebpack((config) => {
// allow React Native modules to be handled with Open Native
config.resolve.alias.set('react-native', '@open-native/core');
// react hooks polyfills
config.resolve.alias.set(
'react',
require.resolve(join(__dirname, './src/react-polyfills'))
);
// configure babel for the desired React Native modules
config.module
.rule('rnmodules')
.include
.add(/node_modules(.*[/\\])+react-native-device-info/)
.add(/node_modules(.*[/\\])+@react-native-community\/netinfo/)
.end()
.use('babel-loader')
.before('ts-loader')
.loader('babel-loader')
.options({
babelrc: false,
presets: ['module:metro-react-native-babel-preset'],
});
});
return webpack.resolveConfig();
};
Enjoy React Native Modules
You can now use them as you'd expect with TypeScript (or JavaScript):
// React Native is pretty cool
import { getIpAddress, getBatteryLevel } from 'react-native-device-info';
const ipAddress = await getIpAddress();
console.log('IP Address:', ipAddress);
const level = await getBatteryLevel();
const batteryLevel = `${(level * 100).toFixed(0)}%`;
console.log('batteryLevel:', batteryLevel);