DNA Mobile App – Understanding ES6, React, React Native, & Redux – ES6



DNA Mobile App – Understanding ES6, React, React Native, & Redux – ES6

1 0


react-native-presentation

Presentation about ES6, React, React Native, and Redux

On Github TimBuckley / react-native-presentation

DNA Mobile App

Understanding ES6, React, React Native, & Redux

Created by Tim Buckley

Contents

ES6 Advanced JavaScript features React fundamentals What React really does React Native Framework for building native mobile apps using React Redux State management library we use for React Native

ES6

  • Next version of JavaScript
  • All of ES5 (current JavaScript) works in ES6
  • Mostly just syntax sugar - can do everything in plain ES5
  • Works out of the box in React Native

Arrow functions

  • Nicer syntax for anonymous functions
// ES5
function (x, y) {
  return x + y
}

// ES6
(x, y) => x + y

// Example
var bozoItems = items.filter(item => item.is_bozo)

// Can also use multiline.
var sum = (x, y) => {
  console.log('The sum is...')
  return x + y
}
            

Arrow functions (cont)

  • Side benefit: this keyword does not change binding inside the function
// ES6
function Person(){
  this.age = 0
  // var self = this // No longer necessary.

  setInterval(() => {
    this.age++ // |this| properly refers to the person object
  }, 1000)
}
var p = new Person()
            

Const and let

  • New versions of var
  • let - can be reassigned, follows scope
  • const - cannot be reassigned
let a = 1
a = 2 // OK

const b = 1
b = 2 // -> ERROR

const nums = [1, 2, 3, 4]
nums.push(5) // OK. Variable can be modified, just not reassigned.
            

Const and let (cont.)

  • Adhere to block scope (yay!)
  • Not hoisted outside of scope
function foo() {
  if (true) {
    const myvar = 1
    console.log(myvar) // prints 1
  }

  try {
    console.log(myvar)
  } catch(ex) {
    console.log('Cannot access myvar outside its block')
  }
}
foo()
            

Default parameters

// ES5
function favoriteThings(pie, num) {
  pie = pie || 'apple'
  num = num || 7

  return pie + num
}
favoriteThings() // 'pie7'

// ES6
function favoriteThings(pie = 'apple', num = 7) {
  return pie + num
}
favoriteThings() // 'pie7'
            

Spread Operator

  • "Breaks out" key-values in obj, or elements in list
  • Similar to Python's splat operator (*args)
const myObj = {a: 1, b: 2, c: 3, d: 4}
const newObj = { ...myObj, d: 40, e: 50}
console.log(myObj) // {a: 1, b: 2, c: 3, d: 4}
console.log(newObj) // {a: 1, b: 2, c: 3, d: 40, e: 50}

const letters = ['b', 'c', 'd']
const newLetters = ['a', ...letters, 'e']
console.log(letters) // ['b', 'c', 'd']
console.log(newLetters) // ['a', 'b', 'c', 'd', 'e']
            

Destructuring

const numbers = [10, 20, 30, 40, 50]
const [first, ...middle, last] = numbers
console.log(first, last) // 10, 50
console.log(middle) // [20, 30, 40]

const position = {lat: 42, lng: 17, alt: 100}
const { lat, lng } = position
console.log(lat, lng) // 42, 17

const printLoc = ({lat, lng, alt}) => console.log(alt, lat, lng)
printLoc(position) // 100, 42, 17
            

Import/Export

// Importing
// ES5
var React = require('react')
var Text = React.Text
var View = React.View

// ES6
import React, { Text, View } from 'react'
            
// Exporting
// ES5
modules.export = Model

// ES6
export { myFunc, name2, ..., nameN }
export default Model
export default function (…) {…} // also class
export default function name1(…) { … } // also class
            

Classes

  • Somewhat controversial ¯\_(ツ)_/¯
// ES5
function Hello(name) {
  this.name = name
  this.hello = function hello() {
    return 'Hello' + this.name
  }
}

// ES6
class Hello {
  constructor(name) {
    this.name = name
  }
  hello() {
    return 'Hello ' + this.name
  }
}
            

Generator functions

  • A "pausable" function.
  • Use yield to return a generator object
  • Calling gen.next() returns next object
function* idMaker(){
  let index = 0
  while(index < 3) {
    yield index++
  }
  return 'No more ids'
}

const genObj = idMaker()

genObj.next() // {done: false, value: 1}
genObj.next() // {done: false, value: 2}
genObj.next() // {done: false, value: 3}
genObj.next() // {done: true, value: 'No more ids'}
            

Generator functions (cont.)

  • Q: So... why do this?
  • A: You can write async code in a synchronous fashion(!)
function* getRecentUsernames() {
  const items = yield fetchRecentItems()
  const authors = items.map(i => i.author)
  const [ users, profiles ] = yield [
    fetchUsers(authors),
    fetchProfiles(authors),
  ]
  return { users, profiles }
}
console.log(genWrapper(getRecentUsernames))
            

Async Functions

  • Does same as generators, but without wrapper
async function getRecentUsernames() {
  const items = await fetchRecentItems()
  const authors = items.map(i => i.author)
  const [ users, profiles ] = await Promise.all([
    fetchUsers(authors),
    fetchProfiles(authors)
  ])
  return { users, profiles }
}

console.log(getRecentUsernames())
            

React Fundamentals

  • Facebook library for building user interfaces.
  • The "V" in MVC
  • Simplifies ui to: (state) => ui
  • Uses Virtual DOM to calculate minimal number of DOM changes necessary, then does them.
  • Encourages nested components.
  • One-way data binding. Predictible == Easy to Test

Nesting components

Source: http://teropa.info/blog/2015/03/02/change-and-its-detection-in-javascript-frameworks.html
Source: 
								http://teropa.info/blog/2015/03/02/change-and-its-detection-in-javascript-frameworks.html
						

JSX Example

Transpiled JSX

3 ways to write React Components

React Native

React Native: just React for mobile

HTML vs Native nodes

Styling in React Native

Styling: Flexbox

Chrome Debugger: Just like web dev

Hot Reloading

(Demo)

Redux

  • State management library we use for React Native
  • NOT an MVC style. Functional Programing paradigm
  • Most popular library for React/RN (even more than FB's own Flux)
  • Three easy pieces:
    • Store: One source of truth for app (Big ol' JS object)
    • Actions: Events/user interactions that change app (JS objects).
    • Reducers: Transforms current state into new state (Pure JS function)

Store

  • Holds global app state
  • React components subscribe to Store and re-render when state changes
{
  newsfeed: {
    items: [item1, item2, ...],
    error: '',
    loading: false
  },
  composeItem: {
    body: '...',
    nbhds: [],
  },
  global: {
    user: {
      username: 'user1'
    }
  },
  (...)
}
            

Actions

  • Represents any event that can change state.
    • (user actions, server responses, etc.)
  • Simple JavaScript objects (must have a "type" property)
{
  type: 'SELECTED_ITEM',
  itemId: 123
}

{
  type: 'NEWSFEED_LOADED',
  items: [item1, item2, ...]
}
            

Reducers

  • Only way app state in the Store can change.
  • (currentState, newAction) -> newState
  • Pure function that takes old state + action and emits a new state
function itemsReducer(state = initialState, action = {}) {
  switch (action.type) {
    case 'FAV_ITEM':
      const { itemId } = action
      return {
        ...state,
        items: state.items.map(i =>
                        i.id === itemId ? favItem(i) : i)
      }
    default:
      return state
  }
}
            

Bonus piece: Middleware

  • Optional. Sit between actions and reducers
  • Allow actions to be changed/delayed/stopped before hitting reducers
  • Examples of middleware:
    • redux-promise - Resolves any promises in Actions before reducing
    • redux-logger - Logs new actions to console
    • redux-thunk - executes

THE End

DNA Mobile App Understanding ES6, React, React Native, & Redux Created by Tim Buckley