62
Cross Platform Development with React Native Ken Wheeler | @ken_wheeler

Mobile Day - React Native

Embed Size (px)

Citation preview

Page 1: Mobile Day - React Native

Cross PlatformDevelopmentwith React NativeKen Wheeler | @ken_wheeler

Page 2: Mobile Day - React Native

What is ReactNative?

Page 3: Mobile Day - React Native

Cross platform native app library

Write native apps in Javascript

Renders to real native UI

Page 4: Mobile Day - React Native

First, lets talkabout React

Page 5: Mobile Day - React Native

UI library developed at Facebook

Pitched as "just the view layer"

Robust component system

Virtual DOM

The new hotness

Page 6: Mobile Day - React Native

class Test extends React.Component { render() { return ( <div> <p>I'm a component!</p> </div> ) } }

Page 7: Mobile Day - React Native

JSX<div> <p>I'm a component!</p> </div> React.DOM.div(null, React.DOM.p(null, "I'm a component!") );

Page 8: Mobile Day - React Native

Propsclass Test extends React.Component { render() { return <p>{this.props.name}</p> } } //Usage <Test name="Ken"/>

Page 9: Mobile Day - React Native

Prop ValidationTest.propTypes = { name: PropTypes.string }; Test.defaultProps = { name: "Default" };

Page 10: Mobile Day - React Native

Stateclass Test extends React.Component { state = { count: 1 }; render() { return <p>{this.state.count}</p> } }

Page 11: Mobile Day - React Native

setStatethis.setState({ count: 2 });

Page 12: Mobile Day - React Native

Eventsclass Test extends React.Component { increment() { ... } render() { return ( <button onClick={this.increment}> Increment </button> ); } }

Page 13: Mobile Day - React Native

ComponentLifecycle

Page 14: Mobile Day - React Native

componentWillMountcomponentDidMountcomponentWillUnmount

componentWillReceivePropscomponentWillUpdatecomponentDidUpdateshouldComponentUpdate

Page 15: Mobile Day - React Native

What about data?

Page 16: Mobile Day - React Native

Unidirectional Data Flow

Page 17: Mobile Day - React Native

Flux Architecture

Page 18: Mobile Day - React Native

Smart Components

Page 19: Mobile Day - React Native

Reduxhttps://github.com/reactjs/redux

Relayhttps://github.com/facebook/relay

RxJShttps://github.com/ReactiveX/RxJS

Page 20: Mobile Day - React Native

React Native

Page 21: Mobile Day - React Native

Why use React Native?

Cross Platform

"Native Feel"

One Language

Live Reload

OTA Updates

Page 22: Mobile Day - React Native

Why is makes sense forbusiness

Fast Development Cycles

Fast Deployment Cycle

Resource Interoperability

One Team

Page 23: Mobile Day - React Native

How React Native Works

Page 24: Mobile Day - React Native

Primitivesclass Test extends React.Component { render() { return ( <View> <Text>I'm a component!</Text> </View> ) } }

Page 25: Mobile Day - React Native

View Components

Page 26: Mobile Day - React Native

ViewTextImageListViewMapViewNavigatorScrollView

ModalPicker

RefreshControlSwitchTextInputWebViewTouchable*

Page 27: Mobile Day - React Native

Device APIs

Page 28: Mobile Day - React Native

AlertAnimatedAppState

AsyncStorageCameraRollDimensions

LinkingNetInfoPixelRatioPanResponderStyleSheet

LayoutAnimation

Page 29: Mobile Day - React Native

Poly�lls

Page 30: Mobile Day - React Native

FlexboxGeolocationNetworkTimersColors

Page 31: Mobile Day - React Native

Networking

Page 32: Mobile Day - React Native

Fetchfetch(API_URL) .then(res => res.json()) .then(data => { console.log(data); }) .catch(error => { console.warn(error); });

Page 33: Mobile Day - React Native

Async/Awaitasync function getData() { try { const res = await fetch(API_URL); const data = await res.json(); console.log(data); } catch(e) { console.warn(e) } }

Page 34: Mobile Day - React Native

Styling & Layout

Page 35: Mobile Day - React Native

StyleSheetconst styles = StyleSheet.create({ container: { backgroundColor: "#ccc", padding: 10, margin: 10, borderRadius: 3, borderWidth: 2 } });

Page 36: Mobile Day - React Native

Applying Stylesclass Container extends React.Component { render() { return ( <View style={styles.container}/> //... child components </View> ) } }

Page 37: Mobile Day - React Native

Flexboxconst styles = StyleSheet.create({ layout: { flexDirection: "row", alignItems: "center", justifyContent: "center" }, tiles: { flex: 1 } });

Page 38: Mobile Day - React Native

Custom iOSModules

Page 39: Mobile Day - React Native

// MyModule.h #import "RCTBridgeModule.h" @interface MyModule : NSObject <RCTBridgeModule> @end

Page 40: Mobile Day - React Native

// MyModule.m @implementation MyModule RCT_EXPORT_MODULE(); RCT_EXPORT_METHOD(sayName:(NSString *)name){ RCTLogInfo(@"My name is %@", name); } @end // Usage in Javascript: NativeModules.MyModule.sayName("Ken");

Page 41: Mobile Day - React Native

RCT_EXPORT_METHOD(getData:(RCTResponseSenderBlock)callback) { NSArray *data = ... callback(@[data]); } // Usage in Javascript: NativeModules.MyModule.getData(data => { console.log(data); });

Page 42: Mobile Day - React Native

RCT_REMAP_METHOD(getData, resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) { NSArray *data = ... if (data) { resolve(data); } else { NSError *error = ... reject(@"no_data", @"Data fetch error", data); } } // Usage in Javascript: NativeModules.MyModule.getData .then(data => console.log(data)) .catch(err => console.log(err));

Page 43: Mobile Day - React Native

Custom AndroidModules

Page 44: Mobile Day - React Native

public class MyModule extends ReactContextBaseJavaModule { public MyModule(ReactApplicationContext reactContext) { super(reactContext); } @Override public String getName() { return "MyModule"; } @ReactMethod public void sayName(String name) { Log.v("MyModule", "My name is " + name); } } // Usage in Javascript: NativeModules.MyModule.sayName("Ken");

Page 45: Mobile Day - React Native

@ReactMethod public void getData(Callback errorCallback, Callback successCallback try { float data = // ...get data; successCallback.invoke(data); } catch (IllegalViewOperationException e) { errorCallback.invoke(e.getMessage()); } } // Usage in Javascript: NativeModules.MyModule.getData( (err) => console.log(err), (data) => console.log(data) );

Page 46: Mobile Day - React Native

@ReactMethod public void getData(Promise promise) { try { float data = // ...get data; promise.resolve(data); } catch (IllegalViewOperationException e) { promise.reject(e); } } // Usage in Javascript: NativeModules.MyModule.getData .then(data => console.log(data)) .catch(err => console.log(err));

Page 47: Mobile Day - React Native

iOS ViewComponents

Page 48: Mobile Day - React Native

@interface RCTMapView : RCTViewManager @end @implementation RCTMapManager RCT_EXPORT_MODULE() RCT_EXPORT_VIEW_PROPERTY(mapType, MKMapType) - (UIView *)view { return [[MKMapView alloc] init]; } @end //Usage in javascript const RCTMap = requireNativeComponent('RCTMap', null);

Page 49: Mobile Day - React Native

Android ViewComponents

Page 50: Mobile Day - React Native

public class ReactMapManager extends SimpleViewManager<MapView> @Override public String getName() { return "RCTMapView"; } @ReactProp(name = "mapType") public void setMapType(ReactMapView view, @Nullable int mapType googleMap.getMap().setMapType(mapType); } @Override public ReactMapView createViewInstance(ThemedReactContext context return new MapView(context, Fresco.newDraweeControllerBuilder } } //Usage in javascript const RCTMap = requireNativeComponent('RCTMap', null);

Page 51: Mobile Day - React Native

React NativeTooling

Page 52: Mobile Day - React Native

DebuggingChrome Devtools

Nuclide

Redbox

Yellowbox

Page 53: Mobile Day - React Native

Pro�lingSystrace

Perf Monitor

Instruments (iOS)

Page 54: Mobile Day - React Native

JS Tooling

Page 55: Mobile Day - React Native

ES6const add = (a, b) => a + b; // Arrow functions let { name, address, ...info } = this.props; // Destructuring let state = { // Object rest spreads ...state, name }; class Test { // ES6 Classes getName() { return "Test"; } }

Page 56: Mobile Day - React Native

Flowtypefunction getData(url: string, callback: Function): Object { return fetch(url) .then(res => res.json()) .then(data => callback(data)); }

Page 57: Mobile Day - React Native

TestingMocha/Jest

react-addons-test-utils

Enzyme

react-native-mock

Appium

Page 58: Mobile Day - React Native

Third PartyTooling

AppHub

CodePush

Reindex

AppBoy

Page 59: Mobile Day - React Native

RNPM

Page 60: Mobile Day - React Native

Om & Elm Native

Page 61: Mobile Day - React Native

ExponentJSNo Xcode required

Distribute apps to anyone with theapp

Exponent XDE

Exponent App

Available in the App Store

Page 62: Mobile Day - React Native

Demoexp://exp.host/@thekenwheeler/mobile-day-demo