React Native FTL Crash course

Don't forget to record screen

Vladimir Novick

Web Architect & Consultant

Web / Mobile

VR/AR/MR

IoT

mail: vnovick@gmail.com

twitter: @VladimirNovick

github: vnovick

facebook: vnovickdev

Assumptions

Web Architect & Consultant

  • You know Ecmascript 2015
  • You are familiar with ReactJs
  • You are eager to learn

What is React Native

Hybrid app

React Native lets you build mobile apps using only JavaScript. It uses the same design as React, letting you compose a rich mobile UI from declarative components.

Hybrid app

Actual Mobile app

so you build

Motivation

  • Code reuse between mobile Platforms and even web
  • Smaller development team able to handle both IOS and Android
  • Sticking to the same ecosystem as on web
  • Declarative and more functional style of programming with React
  • Styling using modern CSS techniques in mobile world

Architecture

  • Main thread - layout, measuring, drawing

 

  • JS thread - event loop executing js code and sending batched updates before next frame renders (60fps)

 

  • Shadow thread - calculates layout changes

 

  • Native Modules thread - platform API

Execution flow

Bridge

Execution flow

Getting started

With native code

Only JS and expo SDK

Getting started

With native code

Only JS and expo SDK

React Native CLI

IOS Setup

Android Setup

What is Expo

Built on top of React Native

Desktop XDE

Additional native APIs

Mobile Client

Expo Snack playground

Expo XDE

  • Share your project in Expo Client app
  • Develop on device without additional setup
  • Manages react native packager processes
  • Additional logging
  • Publishing

Expo Project lifecycle

CRNA

Can be viewed in Expo XDE

 

Can be ejected to vanilla React Native

 

Can be ejected to React Native + ExpoKit

Running your app

  • CRNA and Expo: from Expo XDE

  • Vanilla:  react-native run-ios

Folder Structure

CRNA

CRNA ejected

react-native-cli

Let's take a look at the code

import { AppRegistry } from 'react-native';
import App from './App';

AppRegistry
    .registerComponent('testproject', 
        () => App
);

index.ios.js / index.android.js

React native retrieves files based on environment extensions

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';

export default class App extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <Text>
            Open App.js to start working on your app!</Text>
        <Text>
            Changes you make will automatically reload.</Text>
        <Text>
            Shake your phone to open the developer menu.</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

App.js

Dev tools

Dev tools

Dev tools

npm install -g react-devtools
react-devtools 

Yoga

Yoga is a cross platform layouting engine used in RN

Styling your apps looks like CSS in JS

Yoga

Yoga is a cross platform layouting engine used in RN

const styles = {
  message: {
    width: '70%',
    margin: 10,
    padding: 10,
    backgroundColor: 'white',
    borderColor: '#979797',
    borderStyle: 'solid',
    borderWidth: 1,
    borderRadius: 10
  },
  incomingMessage: {
    alignSelf: 'flex-end',
    backgroundColor: '#E1FFC7'
  }
}

const Message = ({ item }) => (
  <View style={[
      styles.message, item.incoming &&
      styles.incomingMessage
    ]}>
    <Text>{item.message}</Text>
  </View>
)

Stylesheet

import { Stylesheet } from 'react-native';

const styles = Stylesheet.create({
  message: {
    width: '70%',
   //...
})

Making a stylesheet from a style object makes it possible to refer to it by ID instead of creating a new style object every time.

Navigation

https://reactnavigation.org

import React from 'react';
import { StackNavigator } from 'react-navigation';

const AppNavigator = StackNavigator({
  home: { screen: Home },
  chat: { screen: ChatScreen }
});

export default class extends React.Component {
  render(){
    return (
      <AppNavigator />
    )
  }
}

Navigation

StackNavigator - screens where you need back functionality

TabNavigator - screens where you need to switch between tabs

DrawerNavigator - drawer style menu

Navigation

//...
export default class Home extends React.Component {

  static navigationOptions = {
    title: "Home Screen"
  }

}
// ...
  render(){
    return (
      <View style={styles.container}>
        <Button title="Navigate to ChatScreen"
          onPress={() => this.props.navigation.navigate('chat', { name: 'John' })}/>
      </View>
    )
  }

Navigation Flow

Welcome

Main

Screen 1

Screen 2

Settings

Settings2

TabNavigator without actual tabs

TabNavigator

StackNavigator

Animations

Layout animation

Animated

Layout animation

         Pros:

  • Applied to all style properties of component
  • No need for specific values (heights/ widths)

Cons:

  • Less configurable

  • Animates everything on next render

  • setState during animation won't affect current animation

Animated

         Pros:

  • Extremely configurable
  • Can target specific components

Cons:

  • Utilizes requestAnimationFrame by default
  • If setState takes time animations can stutter

Examples

Layout animation

Animated

Networking

fetch api

Web Sockets

Platform APIs

AccessibilityInfo, ActionSheetIOS, AdSupportIOS, Alert, AlertIOS, Animated, AppRegistry, AppState, AsyncStorage, BackAndroid, BackHandler, CameraRoll, Clipboard, DatePickerAndroid, Dimensions, Easing, Geolocation, ImageEditor, ImagePickerIOS, ImageStore, InteractionManager, Keyboard, LayoutAnimation, Linking, NativeMethodsMixin, NetInfo, PanResponder, PermissionsAndroid, PixelRatio, PushNotificationIOS, Settings, Share, StatusBarIOS, StyleSheet, Systrace, TimePickerAndroid, ToastAndroid, Vibration, VibrationIOS, Layout Props, Shadow Props

Expo SDK APIs

Accelerometer, Amplitude, AppLoading, Art, Asset, Audio, AV, BarCodeScanner, BlurView, Branch, Constants, Contacts, DocumentPicker, ErrorRecovery, Facebook, FacebookAds, Font, GLView, Google, Gyroscope, ImagePicker, KeepAwake, LinearGradient, Location, MapView, Notifications, Pedometer, Permissions, Segment, SQLite, Svg, takeSnapshotAsync, Util, Video, WebBrowser

Dealing with native modules

linking packages with native modules

Writing your own native modules

Objective C

// MyNativeModule.h
#import <React/RCTBridgeModule.h>

@interface MyNativeModule : NSObject <RCTBridgeModule>
@end
// MyNativeModule.m
#import "MyNativeModule.h"
#import <React/RCTLog.h>
@implementation MyNativeModule

// To export a module named ExsportedModuleName
RCT_EXPORT_MODULE(ExsportedModuleName);

RCT_EXPORT_METHOD(logInfo:(NSString *)text)
{
  RCTLogInfo(@"Logging from my native module %@", text);
}

@end
import { NativeModules } from 'react-native';
const logger = NativeModules.ExsportedModuleName;

logger.logInfo('Test message');

Java

Step 1: Create the module

create class that extends ReactContextBaseJavaModule 

Override createNativeModules method

Expose methods to JS using @ReactMethod

Step 2: create a package for module and register it

create class that implements ReactPackage

Deployment

Code Push 

App Hub

deploy JS bundles without app store update

Contact me for Consultation

React Native FTL Crash course

By vladimirnovick

React Native FTL Crash course

  • 2,045