React native: building native iOS apps with javascript

  • View
    944

  • Download
    5

  • Category

    Mobile

Preview:

Citation preview

React NativeCodePot 2015

Jarek Potiuk CTO, Polidea

1

Useful links

● http://www.reactnative.com/ - your starting page for everything react native

● http://facebook.github.io/react-native/docs/ - react native documentation

● http://facebook.github.io/react/ - your starting point to learn about react patterns and react.js

● http://facebook.github.io/react/docs/ - react (react.js) docs

2

Workshop resources

● Github repository: https://github.com/potiuk/codepotreact

● Additional files for tasks: https://goo.gl/6evr5g

3

● not a Hybrid App framework● no HTML (DOM)● no CSS (as we know it)● no cross-platform app tool● no, you cannot use jquery plugins with it

What RN is not

4

A JAVASCRIPT LIBRARY FOR BUILDING USER INTERFACES

What RN is

Atwood's Law: any application that can be written in JavaScript, will eventually be written in JavaScript.

5

● independent from:○ data models○ internal application logic○ application state machine○ design patterns for application architecture

● no two-way data-binding● great for modern architectures (ex. DDD)

and frameworks (ex. Flux)

No application architecture binding

6

Prerequisites

● Have MacBook● Register at http://apple.developer.com● Download XCode (7-beta or 6.4) and

simulator (Preferences -> Downloads) !● Fullfill prerequisites from: http://facebook.

github.io/react-native/docs/getting-started.html

7

TASK1. Create and run application

● Create project> npm install -g react-native-cli

> react-native init CodepotReactMine

● In package.json, change react to “^0.10.0-rc” and update:

> npm update● Open .xcodeproject in XCode● Run the app in the simulator

8

Take a good look at the files

● IntelliJ has good support (JSX Harmony)● package.json -> js dependencies● index.ios.json -> main file● AppDelegate.m -> running app● node_modules -> libraries (from package.

json)● iOS -> native “runner”● CodepotReactTests

9

Packager

● runs in the background● bundles the files● builds source maps● serves the bundle file● can be used to build phone deployment

10

Components - fundamental building blocks

● components are state machines● properties● state● internal logic● render method● JSX-based view model● style● can be nested

11

Component Example

12

Rethink established best practicesTM

13

Everything* is javascript

● code is javascript

● styles are … javascript

● JSX is … javascript

● layout is … javascript

14

Not your grand-father’s javascript

● use ‘strict’● Javascript runtime: JavascriptCore/V8● io.js platform (node rewritten)● ES6 + some ES7 (draft):http://facebook.github.io/react-native/docs/javascript-environment.html#content

● Babel transpiler● @flow - static code compilation

15

JSX

var app = <Nav color="blue"> <Profile>click</Profile> </Nav>

var Nav, Profile;var app = React.createElement( Nav, {color:"blue"}, React.createElement(Profile, null, "click"));

Always Uppercase Component Names

16

Styles

● similar to CSS● no class● dash-separated => camelBack (mixedCase)● subset of CSS only● flexbox layout● is done in Javascript● can be easily and predictably combined

17

Layout

● Flexbox + some css● Implemented by facebook in … Javascripthttps://github.com/facebook/css-layout

● Subset of web layout● No baggage ● Side note - it transpiles to C and Java (!)

18

Advantages of using JS everywhere*

● Simple management and coordination● Get rid of CSS/HTML baggage● Can be optimized better● Your styles and views more dynamic● easier reuse of styles● everything for component in one place

19

Code for the rest of the workshop

● git clone http://github.com/potiuk/CodepotReact● git checkout TASK1_DONE

● for next tasks: ○ git checkout TASK2_TODO○ implement the TODOs○ git reset --hard○ git checkout TASK2_DONE

20

TASK2: Embedded assets and image tag

https://facebook.github.io/react-native/docs/image.html

● Adding images to .xcasset● Adding Image JSX● Refer to png image with require

21

TASK3: Remote image (and animated)

● Remote URL for the imagehttps://www.dropbox.com/s/5wzad6227j1ugkn/codepot_animate.gif?dl=1

● default image embedded● automated fetch of the image● support for animated gifs ( :D )● unfortunately buggy so we need to

remove it :( and replace with gray image:https://www.dropbox.com/s/2pd4vb1147zupwq/codepot_gray.png?dl=1

22

Developer’s toolchain part 1

● Packager● Error diagnostic● Live Reload● Element Inspections● Profiling● Tests (JS + Obj-C)● IDEs: IntelliJ/WebStorm (Nuclide soon ?? )

23

Developer’s toolchain - Chrome

● Debugging via Chrome tools● Modify data on-the fly with life reload● Use React Chrome extension

https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=en

● View virtual hierarchy and XCode hierarchy● Modify code in debugger

24

“Distributed” documentation

● react-native docs● react docs

○ componentDidMount (component lifecycle)○ refs - referring to components○ ...

● github issues (!)○ AnimationExperimental (old)

https://github.com/facebook/react-native/issues/46

○ ListView implementation https://github.com/facebook/react-native/issues/499

● UIExplorer: https://github.com/facebook/react-native25

● Configure IntelliJ/Webstorm (optional)● Add some life-cycle logs● Set some breakpoints● Enable live reload● Add Chrome React extension● Look at view hierarchy (XCode/Chrome)● Add Chrome workspace mapping● Checkout react-native and run UIExplorer

TASK4: let’s add some code

26

TASK5. Add some action!

● Add button to click (Button ?)● Style the button● Highlight the button on press (extra!)● Console log when the button is pressed

27

Why react?

28

States and Virtual View Hierarchy

Component

StateYour code

Render(in javascript)

View

Virtual View Hierarchy Javascript objects

Image

Image

Text

React

Build native views(native code)

29

State changes

Component

State: {}

Component

State: {workshops: {...} }Update State

Reconciliation

Incremental changesAnimations

Javascript

Native code

30

Incremental updates / animations

31

Update

Remove Create

TASK6: Change component when state changes

● Initial: two images + button● onClick: one image + text● two separate renderings● refactor to separate methods

32

Animations

● LayoutAnimations● Animated● requestAnimationFrame● Navigator scene transitions

33

Layout animations

● React knows both states● Animation of Create/Update/Deletehttps://github.com/facebook/react-native/issues/1440

● Presets: spring, linear, easeInOut● Customisation options:

○ Duration○ Opacity/ScaleXY○ Spring/Linear/EaseInEaseOut

34

Animated

● Fine grained control ● Declarative● Value animations still in javascript● But potential to optimise it (async bridge)● Looks like full native is in the works

35

TASK7: Animate component state change

● Make component changes animate● Try out different animation options● Add second image● Make original image animate up● Make down image animate down● Try various options

36

More complex views reconciliation

● Reconciliation is simple (non-optimal)● How does it know which Image is which?● Imagine list with many items● “key” property is a key to solve it

37

TASK8. Using key to aid animation

● Make the bottom image same as top● Animate the bottom image instead of top

38

Networking

● Fetch - standard (HTML5)● Uses promises● JSON support built in javascript● Dynamic structures are good :)● Asynchronous communication

39

TASK9: fetch data for workshops

● Fetch data: https://backend.codepot.pl/api/workshops/

● Response is a json file (Hint! .json() )● Save workshops to “workshops” key in

state● Update console logs● Make the text showing what’s going on:

○ “Fetching” -> “Fetched <number> of workshops”

40

ListView

● NOT the same as UITableView● Immutable data (clone)● Sections support● Still problems with really long lists● Other implementations exist https://github.

com/aksonov/react-native-tableview

41

TASK9. Show workshops in list view

● Add conditional button “show list” after workshops are fetched

● Replace image with list after it’s clicked● Change initial size (gotcha!)

42

Componentisation

● The logic is in one index.ios.js● It’s more and more difficult to reason

about it● Components

○ small○ self-contained○ can be moved around

● Properties● Common parts (ex. styles)can be re-used

43

Separating components

● Separate components to separate files● module.exports● require(“<relative path>”)● Components:

○ Show list conditional button○ Initial screen○ Waiting screen○ List screen

44

TASK11: ShowListButton as separate component

● ShowListButton conditionally shows● “isVisible” bool property● “clicked” callback function

45

TASK12: Common styles extracted

● separate out button style to common/CommonStyles.js

46

TASK13: Separate ListView to a separate List component

● Put list view to separate component passing workshops to it

● Make sure no ListView is needed in the index.ios.js

47

TASK14: separate out initial screen

● Separate out the intial screen to separate component

● Pass callbacks to the components to fetch data (!)

48

Extras

49

Navigators

● NavigatorIOS○ small, limited API○ Javascript + ObjC○ animations/behoviour of native UIKit navigator○ navigation bar can be only slightly modified○ some bugs (community maintained)

● Navigator○ Extensive API○ Javascript○ Navigation/BreadCrumbNavigation○ Animations are not perfect (yet)

50

Integration with ObjC/Swift

● Custom Access to APIshttp://facebook.github.io/react-native/docs/native-modules-ios.html#content

● Custom native UI componentshttp://facebook.github.io/react-native/docs/native-components-ios.html#content

● Direct Properties manipulation http://facebook.github.io/react-native/docs/direct-manipulation.html#content

● RCTView can be embedded in native apphttp://facebook.github.io/react-native/docs/embedded-app-ios.html#content

● Can work with cocoapods

51

Native/Javascript bridge

● Not in UI thread● Asynchronous, serializable communication● Batching requests● Lots of optimisations already● Potential optimisations in the future● Flexible threading model

52

Deployment options

53

Internal Architecture

54

Standalone app

55

Development

56

Debugging

57

Remote server

58

Live update - AppHub

59

What Facebook wants to achieve?

What they tell● Learn once - write anywhere● No “cross-platform app framework”● Less complex apps

What they don’t tell● Common code shared as libs● Dynamic app updates (A/B testing)

60

Is it ready yet?

● Still beta and changing fast● Still some (small) issues with performance● Have not tested with really big application● Some components are of beta quality● Some components done by community● Community is small but growing (Stack

Overflow)● Documentation is heavily “distributed”

61

Recommended