https://assets.wolfmatrix.com/uploads/2019/01/wonder-of-react-native-1.jpg

Wonders Of React Native

Pratik Manandhar
January 3, 2019 - 8 min read

As a frontend developer here at Wolfmatrix, I was tasked to develop a mobile application using React Native – a cross-platform framework for developing mobile apps. Now, as a developer, I am always on the edge to learning something new. And as a web developer, I have always been fascinated by and eager to work in mobile development. So this was an awesome opportunity to dabble my hands in the wonders of React Native and create something #wonderful.

So here I am sharing my experience working with React Native, what allowed for the switch, and the lessons learned from this endeavor. This article has been written from a “so, you are a web developer and want to build native?” perspective.

Switching gears

“Curiosity is a developer’s biggest strength”

A curious developer is one who never stops learning, be it for his career, a dream project or for his own personal tinkerings. Obviously, that zest rubbed off on me as well. I already had experiences working with React.js and some relatively short experience in Android Development. So the next step was React Native.

As luck would have it, we got a project at our hands for a mobile application. In the meeting, the discussion was going on as to how we would proceed and we came upon a choice for developing the app in either a React.js app rendered on an Android WebView or write the whole app in React Native. 

I began writing prototypes for both of these choices. While the Android Webview way would be easier in terms of the development process, there were challenges in contrast to developing in React Native. For instance, writing native code and accessing GPS modules would be a hassle. After some careful considerations, we decided to walk the React Native walk.

And, thus began my journey in the wonderful land of React Native.

What is React Native anyways?

React Native is a framework for building cross-platform applications using Javascript (mainly) in Facebook’s own React library.

But you may conjure up the question – “What makes React Native so special?” and I won’t judge you. It is a valid question if you put into perspective the fact that there are other frameworks that fulfill the very promise – “single code, multiple platforms”.

The catch here is, while frameworks such as Ionic do develop applications that can be run on different platforms, their nature is such that the application is rendered on a mobile webview. We can call them hybrid applications while a React Native app can be called cross-platform application.

 “Learn once, Write everywhere”

React Native is different from the other frameworks as RN renders native UI components. This is what gives a React Native application a native look and feel. For instance, when you write a Javascript code to render any Text on the screen using the <Text> tag, React Native renders a native component to display the text on the device screen – TextView in Android, and UILabel in iOS. The way this is done is through a Javascript bridge, which renders the Native Components for the device platform that it’s running on( I know, pretty slick!!).

React Native – The Good

  • React Native offers a truly native user experience, unlike hybrid tools that merely provide a native-style wrapper for browser-based apps.
  • Apps built with React Native are known to be reliable and stable.
  • In addition to developing new apps, React Native can be used to upgrade existing native apps.
  • React has an awesome “hot reloading” feature that saves further development time. It enables changes made in the source code of an app to immediately load into iOS and Android app variants. This eliminates the waiting time associated with reloading each app to refresh for the changes to be applied.

React Native – The Bad

  • Third-party component libraries are not guaranteed to be good quality.
  • App Performance Lacks as Compared to a Pure Native App.
  • Native development is still needed to tap into devices hardware and sensors (GPS, Camera).

React Native Development

Now that we have some insights into what React Native is,  let’s venture into developing a React Native application.

From the get-go, there are two ways to developing mobile apps in RN. The first is with expo – a framework to build React Native applications. The second is (you guessed it…) without expo.

react nativereact native

As you can see in the above image, the left image has android and ios folders. They are missing in the one on the right.

The RN project on the left is created using the command <code>react-native init [project_name]</code>, using which we can write JS code as well as write native code in the respective platform folders. And on the right, the project is developed using the expo framework and initialized with the command <code>expo init [project_name]</code>

Personally, I’d rather develop without using Expo as it allows for writing and reusing native code and functionalities. For the remainder of this article, we will be going the non-expo route 🙂

Let’s run it

After the project has been initialized, the next step is to run the app on a device or an emulator. We will see that we have 4 predefined scripts.

  • npm start or yarn start is used to run the “metro bundler” server in development mode. This node server is responsible for creating the javascript bundle. It also handles the updates to the bundle on code update.
  • react-native run-android command bundles the app and installs and runs it on your connected Android device/emulator.
  • react-native run-ios command bundles the app and installs and runs it on an iOS device/simulator. Keep in mind that you will be needing a Mac to build the ios version, as we are building a native iOS application and because Apple is a jerk.
  • npm test used for running test. Jest is used by default, but you are free to change it to your liking.

react native

If you have been unlucky and ran into some issues while starting your app on the first try, you can check this Troubleshoot page by Facebook to solve known issues with React Native.

Now, that we have successfully run the app on an Android/iOS device, let’s get to the good stuff – The code 😀

import React, {Component} from react;
import {Platform, StyleSheet, Text, View} from react-native;
const instructions = Platform.select({
ios: Press Cmd+R to reload,\n + Cmd+D or shake for dev menu,
android:Double tap R on your keyboard to reload,\n + Shake or press menu button for dev menu,
});
export default class App extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>Welcome to React Native!</Text>
<Text style={styles.instructions}>To get started, edit App.js</Text>
<Text style={styles.instructions}>{instructions}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: center,
alignItems: center,
backgroundColor: #F5FCFF
},
welcome: {
fontSize: 20,
textAlign: center,
margin: 10
},
instructions: {
textAlign: center,
color: #333,
marginBottom: 5
}
})
view raw
App.js
hosted with ❤ by GitHub

The Platform module in React Native is used to write platform dependent code. It returns the platform, in this case, Android or iOS, and it can be used to render a different UI in android and ios devices or execute a piece of code depending on the environment that the app is running on.

React Native also allows writing platform dependent components by naming the component files as component.ios.js and component.android.js and just import the component name into your code. RN will automatically import the respective file based on the platform its running on, thus, eliminating the need to import components conditionally.

Styling

Every app out there is unique, has a different combination of colors, fonts, UI Components and an overall User Experience.

So, how would you introduce styling to a React Native Application? Well, if you’re coming from a background in React.js, you know the styling is done in CSS files or inline styling.

Unfortunately, RN does not accept styling in this way. Instead, styling in a RN application is done directly in the code. So, a styling in css such as {color: red} would be {color: ‘red’}, {font-size: 12} would be {fontSize: 12}.

The StyleSheet module in React Native is an abstraction similar to CSS StyleSheet. The key difference being the styling definitions are written using javascript instead of in a .css file.

Layout

As mentioned earlier, a React Native application is written using React, which uses jsx – writing HTML markup inside javascript. However, the elements that are used in React Native are very different than React. While React uses DOM elements such as div, p, etc. , RN uses a separate set of components to render its UI. For instance, p tags are replaced Text tag.

React Native UI is written using Facebook’s own Yoga library – a Flexbox implementation. If you are a frontend developer like me, then I’m sure you have worked with Flexbox in CSS.

Flexbox works the same way in React Native as it does in CSS on the web, with a few exceptions. The defaults are different, with flexDirection defaulting to column instead of row, and the flexparameter only supporting a single number.

The flex properties for the UI components are defined using a style prop.

<View style={{flex: 1, flexDirection: ‘row’}}>

       <View style={{width: 50, height: 50, backgroundColor: ‘red’/>

       <View style={{width: 50, height: 50, backgroundColor: ‘blue’}} />

       <View style={{width: 50, height: 50, backgroundColor: ‘green’}} />

     </View>

 

Here is the full documentation for the layout props in RN.

Navigation

An application almost always has different screens for different areas of the app. And a  React Native application is not different in this case.

However, an official solution for navigation in React Native is yet to come out. React Native framework hasn’t reached version 1.0 at the time of writing this article. It has been speculated that version 1.0 will be released with a definitive library for navigation.

As for now, there are various third party libraries that can be used for navigation. The most popular one is React-Navigation.

Linking with platform native code

Although a react native application is mostly written in javascript, for the most part, often it so happens that we need to access some native functionalities of the platform, be it android & iOS, of which the javascript counterpart has not been developed yet. Think of some custom functionality that you made for that is specific to your application.

The reason for using native code could be that you have already developed the function in native code and would rather use that instead of writing it again in javascript, or it could also be to leverage the speed and performance of native realm.

Such a scenario presented itself in our client’s application as well. The issue was to link the application to Firebase and log the user details to Crashlytics. Since there wasn’t a readymade solution in React Native, we installed native firebase crashlytics libraries into the iOS/Android versions. Then we wrote wrappers in native code to access these native APIs from the javascript realm.

Implementation in Android

package com.reactnative.example.reactnativemodules;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import java.util.Map;
import javax.annotation.nullable;
import com.crashlytics.android.Crashlytics;
import com.facebook.react.bridge.ReactMethod;
public class CrashlyticsModule extends ReactContextBaseJavaModule{
public CrashlyticsModule(ReactApplicationContext applicationContext){
super(applicationContext);
}
@Override
public string getName(){
return CrashlyticsModule;
}
@Nullable
@Override
public Map<String, Object> getConstants(){
return super.getConstants();
}
@ReactMethod
public void SetUserProfile(string profile){
Crashlytics.setStrint(profile, profile);
}
@ReactMethod
public void Log(String tag, String message){
Crashlytics.log(Log.DEBUG, tag, message);
}
}
package com.reactnative.example;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.reactnative.example.reactnativemodules.CrashlyticsModule;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ReactCrashlyticsPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new CrashlyticsModule(reactContext));
return modules;
}
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}

Here is the documentation on linking native libraries in React Native.

Conclusion…

So, there you have it folks, a dive into the wonders of React Native.

All in all, it was quite a fulfilling experience to develop a mobile application using React Native. The look and feel of the app is same as that of a native app, almost indistinguishable from an application written in native platform language (Java or Swift).

So should you use React Native for your next mobile application? The answer to that question is a rather subjective one as it depends largely on your app requirements. An application that needs heavy computations or relies on native libraries might not benefit from React Native. But, if your app is a rather simple one, with a minimalist use for native APIs then React Native will make an awesome choice.

You can always check out React Native, build something awesome and help the ever-growing open source community of React Native by building custom libraries.

I hope this article has been helpful to you in some way.

Ciao 🙂

Here you can check out the projects we did using React Native.

We open source.

If there is one thing that all of us fundamentally believe in then its this: "We should cooperate with others and compete with ourselves". Open source helps us achieve the same plus the culture of innovation and continuous learning.

GitHub