Upgrade to Pro — share decks privately, control downloads, hide ads and more …

React Native Workshop

React Native Workshop

React Native introductory workshop

Victoria Quirante

September 26, 2019
Tweet

More Decks by Victoria Quirante

Other Decks in Programming

Transcript

  1. September 2019
    Introduction to

    React Native
    Victoria Quirante

    View Slide

  2. Victoria Quirante
    I write code at Limenius.
    We build tailor-made projects,
    and provide consultancy
    and formation.
    And we are very happy users of React and React Native.

    View Slide

  3. https://github.com/Limenius/workshop-react-native.git
    And run git fetch
    https://speakerdeck.com/victoriaq/react-native-workshop
    Before we start

    Please go to where you have cloned the repo
    of the project

    View Slide

  4. Goal of the workshop
    To be able to estimate how long would
    it take you to create a first React Native
    project (and if you would enjoy it)
    A big part of it is the tooling

    View Slide

  5. Roadmap:
    What is React Native
    Starting a project
    Working with Styles
    Layout
    Lists
    Navigation
    Networking
    Touching the native side

    View Slide

  6. What is React Native?

    View Slide

  7. Fundamental premise of React
    Give me a state and a render() method
    that depends on it and forget about
    how and when to render.

    View Slide

  8. render() {
    return (

    Click me!
    Clicks: {this.state.count}

    )
    }

    View Slide

  9. render() {
    return (

    Click me!
    Clicks: {this.state.count}

    )
    }
    render() {
    return (

    Click me!
    Clicks: {this.state.count}

    )
    }

    View Slide

  10. render() {
    return (

    Click me!
    Clicks: {this.state.count}

    )
    }
    render() {
    return (

    Click me!
    Clicks: {this.state.count}

    )
    }

    View Slide

  11. render() {
    return (

    Click me!
    Clicks: {this.state.count}

    )
    }
    render() {
    return (

    Click me!
    Clicks: {this.state.count}

    )
    }
    React Native

    View Slide

  12. How is this possible
    Reconciliation
    Determines what parts
    of the tree have changed

    View Slide

  13. How is this possible
    Reconciliation
    Determines what parts
    of the tree have changed
    Rendering
    Actually
    updates the app

    View Slide

  14. How is this possible
    Reconciliation
    Determines what parts
    of the tree have changed
    Rendering
    Actually
    updates the app
    We can have several
    renderers

    View Slide

  15. React targets
    Main
    react-dom react-native
    Web iOS android

    View Slide

  16. React targets
    Main
    react-dom react-native
    Web iOS android
    But also

    View Slide

  17. React targets
    Main
    react-dom react-native
    Web iOS android
    But also
    react-art react-canvas react-three ReactLiberty
    react-worker-dom

    View Slide

  18. React targets
    Main
    react-dom react-native
    Web iOS android
    But also
    react-art react-canvas react-three ReactLiberty
    react-worker-dom
    react-konsul rax
    react-native react-blessed
    react-tvml

    View Slide

  19. React targets
    Main
    react-dom react-native
    Web iOS android
    But also
    react-art react-canvas react-three ReactLiberty
    react-worker-dom
    react-konsul rax
    react-native react-blessed
    react-tvml
    React-GL
    react-vr react-hardware react-fs-renderer react-x11

    View Slide

  20. React targets
    Main
    react-dom react-native
    Web iOS android
    But also
    react-art react-canvas react-three ReactLiberty
    react-worker-dom
    react-konsul rax
    react-native react-blessed
    react-tvml
    React-GL
    react-vr react-hardware react-fs-renderer react-x11
    redocx
    react-titanium React-Gibbon react-pdf react-test-renderer

    View Slide

  21. React targets
    Main
    react-dom react-native
    Web iOS android
    But also
    react-art react-canvas react-three ReactLiberty
    react-worker-dom
    react-konsul rax
    react-native react-blessed
    react-tvml
    React-GL
    react-vr react-hardware react-fs-renderer react-x11
    redocx
    react-titanium React-Gibbon react-pdf react-test-renderer
    ink react-sketchapp

    View Slide

  22. React targets
    Main
    react-dom react-native
    Web iOS android
    But also
    react-art react-canvas react-three ReactLiberty
    react-worker-dom
    react-konsul rax
    react-native react-blessed
    react-tvml
    React-GL
    react-vr react-hardware react-fs-renderer react-x11
    redocx
    react-titanium React-Gibbon react-pdf react-test-renderer
    ink react-sketchapp
    And more

    View Slide

  23. React blessed

    View Slide

  24. React blessed

    View Slide

  25. React Sketch.app

    View Slide

  26. React VR
    Demo

    View Slide

  27. How Native is React Native?
    JS Thread
    Business logic &
    Description of what
    components to render

    View Slide

  28. How Native is React Native?
    JS Thread Main Thread
    UI manipulation
    with native
    components
    Business logic &
    Description of what
    components to render

    View Slide

  29. How Native is React Native?
    JS Thread Main Thread
    UI manipulation
    with native
    components
    Business logic &
    Description of what
    components to render
    Bridge

    View Slide

  30. How much code can we reuse?
    Tip: if you develop in one platform,
    test the app in the other from time to time
    70%? 80%? 90%?

    View Slide

  31. How to start a project

    View Slide

  32. Option 1: expo
    $ npm install -g expo-cli
    $ expo init AwesomeProject

    View Slide

  33. Option 1: expo
    Only JS, no iOS or Android code
    (outside node_modules)
    If you want to modify native code, $ npm run eject
    Uses the Expo app to test in real device
    Meant to have a quick way of trying
    react-native

    View Slide

  34. Option 2: react-native init
    $ npm install -g react-native-cli
    $ react-native init AwesomeProject

    View Slide

  35. Option 2: react-native init
    Complete project with native code
    More control
    Needed to use things like AppCenter
    Doesn’t need external tools to publish to
    the store

    View Slide

  36. Getting our hands dirty

    View Slide

  37. git clone https://github.com/Limenius/workshop-react-native.git
    You are supposed to have done this

    And then yarn install

    View Slide

  38. git checkout master
    react-native run-ios
    And then
    Or
    react-native run-android

    View Slide

  39. Debug tools Cmd + d
    (Cmd + r)
    ctrl+m / cmd+m

    View Slide

  40. Play around
    Open app/App.js with an editor
    Hi there!
    Change the text in
    Try nesting
    Hi there!
    Amigo

    Try changing some styles
    welcome: {
    fontSize: 100,
    textAlign: 'center',
    margin: 10,
    },
    Try placing a console.log(‘hi’) before return(… and see it in
    Chrome dev tools
    https://www.slideshare.net/nachomartin/react-native-workshop-react-alicante

    View Slide

  41. Familiarize with errors
    What happens if we…
    remove a closing tag ()

    Hi there!

    put text not wrapped in
    try to comment a JSX line with //
    return (

    Hi there!


    )
    have two root elements
    use wrong properties for styles ( rename flex -> flexo )
    remove the words export default

    View Slide

  42. Basic components

    View Slide

  43. git checkout elements
    git reset HEAD --hard
    (To discard your changes)

    View Slide

  44. Exercise:
    Play with the basic components
    app/App.js

    View Slide

  45. Exercise: Build new components
    Can you build a new component combining others?
    Ideas: Image with footer (), two buttons that display different alerts
    Can you pass props to that component?
    Ideas: Pass the text of the footer with props, pass also the image, pass the titles of the buttons
    Can your build a component with local state?
    Ideas: Modify the counter to have a “minus 1” button

    View Slide

  46. Style

    View Slide

  47. No CSS. Everything is JS
    borderLeftColor: Colors.accent,
    borderLeftWidth: 9,
    backgroundColor: Colors.backgroundSection,
    padding: 18,
    paddingVertical: 9,
    }}>
    No class
    No dimensions in pixels
    No things like padding: 19 9 3 1
    camelCased
    Use constants

    View Slide

  48. StyleSheet

    const Styles = StyleSheet.create({
    headline: {
    borderLeftColor: Colors.accent,
    borderLeftWidth: 9,
    backgroundColor: Colors.backgroundSection,
    paddingLeft: 18,
    paddingRight: 18,
    paddingTop: 9,
    paddingBottom: 9,
    },
    })

    View Slide

  49. Combination

    const Styles = StyleSheet.create({
    headline: {
    borderLeftColor: Colors.accent,
    borderLeftWidth: 9,
    paddingLeft: 18,
    paddingRight: 18,
    paddingTop: 9,
    paddingBottom: 9,
    },
    })

    View Slide

  50. git checkout styles
    (To discard your changes)
    git reset HEAD --hard

    View Slide

  51. We want to build this

    View Slide

  52. Our first goal is to get this
    (We will practice layouts in the next section)

    View Slide

  53. components/MovieHeader.js
    height: 210
    fontWeight: ‘bold’
    fontSize: FontSizes.LargeTitle
    48x48, rounded
    backgroundColor: Colors.highlight
    color: Colors.text
    color: Colors.text
    fontWeight: ‘bold’
    border: left, size 9, Colors.accent
    padding: 9, 18
    backgroundColor: Colors.backgroundSection

    View Slide

  54. Exercise 1
    84x84
    Colors.text, bold
    Container has: border at bottom size 1, Colors.subtleAccent
    and background is 'white'
    components/ListItemActor.js

    View Slide

  55. Exercise 2
    FontSizes.gigantic
    Colors.background
    Container has: a background with color: Colors.highlight
    components/MainHeader.js
    Image is 40x90
    FontSizes.subhead
    With weight ‘200’
    Colors.background

    View Slide

  56. Dimensions
    import {
    Dimensions,
    } from 'react-native'
    const windowSize = Dimensions.get('window')
    mainImage: {
    height: windowSize.height /3,
    width: undefined
    },
    components/MovieHeader.js

    View Slide

  57. Dimensions
    import {
    Dimensions,
    } from 'react-native'
    const windowSize = Dimensions.get('window')
    mainImage: {
    height: windowSize.height /3,
    width: undefined
    },
    Our image height depends on the
    Height of the window
    Use sparingly
    components/MovieHeader.js

    View Slide

  58. Dimensions
    import {
    Dimensions,
    } from 'react-native'
    const windowSize = Dimensions.get('window')
    mainImage: {
    height: windowSize.height /3,
    width: undefined
    },
    Our image height depends on the
    Height of the window
    Use sparingly
    Exercise: Can you make another style dependant of
    Dimensions?
    What will happen if the device is rotated?
    Can you find anything in the documentation to fix it?
    components/MovieHeader.js

    View Slide

  59. Further reading
    https://www.okgrow.com/posts/react-native-styling-tips
    https://madebymany.com/stories/a-year-of-react-native-styling-part-1
    https://emotion.sh/docs/@emotion/native
    Explore libraries to do CSS in JS

    View Slide

  60. Layouts

    View Slide

  61. This is flexbox realm
    flexDirection
    justifyContent
    alignItems
    alignSelf
    flex
    alignContent
    flexBasis
    flexGrow
    flexShrink
    flexWrap

    View Slide

  62. This is flexbox realm
    flexDirection
    justifyContent
    alignItems
    alignSelf
    flex
    alignContent
    flexBasis
    flexGrow
    flexShrink
    flexWrap
    flexDirection: ‘column' flexDirection: ‘row’
    (Default)

    View Slide

  63. This is flexbox realm
    flexDirection
    justifyContent
    alignItems
    alignSelf
    flex
    alignContent
    flexBasis
    flexGrow
    flexShrink
    flexWrap
    flexDirection: ‘column' flexDirection: ‘row’
    (Default)
    main direction
    cross direction

    View Slide

  64. This is flexbox realm
    flexDirection
    justifyContent
    alignItems
    alignSelf
    flex
    alignContent
    flexBasis
    flexGrow
    flexShrink
    flexWrap
    flexDirection: ‘column' flexDirection: ‘row’
    (Default)
    main direction
    cross direction
    cross direction
    main direction

    View Slide

  65. This is flexbox realm
    flexDirection
    justifyContent
    alignItems
    alignSelf
    flex
    alignContent
    flexBasis
    flexGrow
    flexShrink
    flexWrap
    flexDirection: ‘column’
    (Default)
    ‘flex-start’ ‘flex-end’ ‘center' ‘space-around’ ‘space-between’
    flexDirection: ‘row’
    (Default)
    ‘flex-start’ ‘flex-end’ ‘center' ‘space-around’ ‘space-between’

    View Slide

  66. This is flexbox realm
    flexDirection
    justifyContent
    alignItems
    alignSelf
    flex
    alignContent
    flexBasis
    flexGrow
    flexShrink
    flexWrap
    flexDirection: ‘column’
    (Default)
    ‘flex-start’ ‘flex-end’ ‘center' ‘stretch’ ‘baseline’
    flexDirection: ‘row’
    (Default)
    ‘flex-start’ ‘flex-end’ ‘center' ‘stretch’ ‘baseline’

    View Slide

  67. This is flexbox realm
    flexDirection
    justifyContent
    alignItems
    alignSelf
    flex
    alignContent
    flexBasis
    flexGrow
    flexShrink
    flexWrap
    flexDirection: ‘row’
    ‘baseline’

    View Slide

  68. This is flexbox realm
    flexDirection
    justifyContent
    alignItems
    alignSelf
    flex
    alignContent
    flexBasis
    flexGrow
    flexShrink
    flexWrap
    flexDirection: ‘column’
    alignSelf: ’end’

    View Slide

  69. This is flexbox realm
    flexDirection
    justifyContent
    alignItems
    alignSelf
    flex
    alignContent
    flexBasis
    flexGrow
    flexShrink
    flexWrap
    flex: 1
    flex: 0
    flex: 0

    View Slide

  70. This is flexbox realm
    flexDirection
    justifyContent
    alignItems
    alignSelf
    flex
    alignContent
    flexBasis
    flexGrow
    flexShrink
    flexWrap
    flex: 5
    flex: 2
    flex: 3

    View Slide

  71. This is flexbox realm
    flexDirection
    justifyContent
    alignItems
    alignSelf
    flex
    alignContent
    flexBasis
    flexGrow
    flexShrink
    flexWrap
    flex: 0.5
    flex: 0.2
    flex: 0.3

    View Slide

  72. This is flexbox realm
    flexDirection
    justifyContent
    alignItems
    alignSelf
    flex
    alignContent
    flexBasis
    flexGrow
    flexShrink
    flexWrap
    flex: 25
    flex: 10
    flex: 15

    View Slide

  73. git checkout layout
    (To discard your changes)
    git reset HEAD --hard

    View Slide

  74. Our goal

    View Slide

  75. app/components/MovieHeader.js

    View Slide

  76. app/components/MovieHeader.js

    View Slide

  77. 18
    Exercise 1
    app/components/ListItemActor.js

    View Slide

  78. Exercise 2
    Hint: create subviews if you need them
    Optional: can you come up with a different layout for any of our three components?
    app/components/MainHeader.js

    View Slide

  79. Further reading
    https://facebook.github.io/yoga/docs/getting-started/
    Docs:
    https://github.com/jondot/ReactNativeKatas
    Very good practice:

    View Slide

  80. Lists

    View Slide

  81. Lists are important in mobile

    View Slide

  82. Naive lists, as in the web
    export default class Movie extends Component {
    constructor(props) {
    super(props)
    this.state = {
    movie: movies.find((movie) => movie.name === 'Pulp Fiction')
    }
    }
    render() {
    return (


    { this.state.movie.actors.map(actor => (

    ))}

    )
    }
    }
    app/components/Movie.js

    View Slide

  83. Naive lists, as in the web
    export default class Movie extends Component {
    constructor(props) {
    super(props)
    this.state = {
    movie: movies.find((movie) => movie.name === 'Pulp Fiction')
    }
    }
    render() {
    return (


    { this.state.movie.actors.map(actor => (

    ))}

    )
    }
    }
    Important to help the reconciler do its work
    app/components/Movie.js

    View Slide

  84. Exercise
    git checkout lists
    Can you build a list of movies in
    app/components/MovieList.js ?
    (To discard your changes)
    git reset HEAD --hard

    View Slide

  85. FlatList
    Highly optimized List component
    Features:
    • Scroll loading (onEndReached).
    • Pull to refresh (onRefresh / refreshing).
    • Configurable viewability (VPV) callbacks (onViewableItemsChanged / viewabilityConfig).
    • Horizontal mode (horizontal).
    • Intelligent item and section separators.
    • Multi-column support (numColumns).
    • scrollToEnd, scrollToIndex, and scrollToItem.

    View Slide

  86. FlatList
    render() {
    return (


    data={this.state.movie.actors}
    renderItem={({item}) =>

    }
    />

    )
    }
    app/components/Movie.js

    View Slide

  87. FlatList

    View Slide

  88. FlatList
    What about the keys?

    View Slide

  89. FlatList
    What about the keys?
    data={this.state.movie.actors}
    keyExtractor={item => item}
    renderItem={({item}) =>

    }
    />

    View Slide

  90. FlatList
    What about the keys?
    data={this.state.movie.actors}
    keyExtractor={item => item}
    renderItem={({item}) =>

    }
    />

    View Slide

  91. FlatList
    Scrolleable area
    data={this.state.movie.actors}
    keyExtractor={item => item}
    renderItem={({item}) =>

    }
    />

    View Slide

  92. FlatList
    Desired scrolleable area

    View Slide

  93. FlatList
    Desired scrolleable area
    data={this.state.movie.actors}
    ListHeaderComponent={}
    keyExtractor={item => item}
    renderItem={({item}) =>

    }
    />

    View Slide

  94. FlatList
    Desired scrolleable area
    data={this.state.movie.actors}
    ListHeaderComponent={}
    keyExtractor={item => item}
    renderItem={({item}) =>

    }
    />

    View Slide

  95. Exercise
    Can you use FlatList in
    app/components/MovieList.js ?
    git checkout flatlists
    item => item
    reminder
    In this case works as
    function(item) {
    return item
    }
    git reset HEAD —hard
    (To discard your changes)

    View Slide

  96. Further reading
    https://facebook.github.io/react-native/blog/2017/03/13/
    better-list-views.html
    Read the docs of the components:
    FlatList
    SectionList
    VirtualizedList

    View Slide

  97. Navigation

    View Slide

  98. Navigation

    View Slide

  99. react-navigation

    View Slide

  100. Several options
    StackNavigator TabNavigator DrawerNavigator Or combine them

    View Slide

  101. Several options
    StackNavigator TabNavigator DrawerNavigator Or combine them

    View Slide

  102. Several options
    StackNavigator TabNavigator DrawerNavigator Or combine them

    View Slide

  103. Several options
    StackNavigator TabNavigator DrawerNavigator Or combine them

    View Slide

  104. git checkout navigation
    yarn install
    cd ios; pod install
    Let’s do it
    (To discard your changes)
    git reset HEAD --hard
    If iOS

    View Slide

  105. Let’s do it
    const AppNavigator = createStackNavigator({
    Home: { screen: MovieList },
    Movie: { screen: Movie },
    }, {
    navigationOptions: {
    headerTintColor: Colors.accent,
    headerStyle: Styles.header,
    }
    })
    const App = createAppContainer(AppNavigator)
    app/App.js

    View Slide

  106. Let’s do it
    const AppNavigator = createStackNavigator({
    Home: { screen: MovieList },
    Movie: { screen: Movie },
    }, {
    navigationOptions: {
    headerTintColor: Colors.accent,
    headerStyle: Styles.header,
    }
    })
    const App = createAppContainer(AppNavigator)
    app/App.js
    export default class MovieList extends Component {
    static navigationOptions = {
    title: 'Movies',
    }
    //…
    app/components/MovieList.js

    View Slide

  107. Let’s do it
    const AppNavigator = createStackNavigator({
    Home: { screen: MovieList },
    Movie: { screen: Movie },
    }, {
    navigationOptions: {
    headerTintColor: Colors.accent,
    headerStyle: Styles.header,
    }
    })
    const App = createAppContainer(AppNavigator)
    app/App.js
    export default class MovieList extends Component {
    static navigationOptions = {
    title: 'Movies',
    }
    //…
    app/components/MovieList.js
    data={this.state.movies}
    ListHeaderComponent={}
    keyExtractor={item => item.name}
    renderItem={({item}) =>
    underlayColor={Colors.subtleAccent}
    activeOpacity={0.5}
    onPress={() => navigate('Movie', {name: item.name})}
    >




    }
    />
    In render()

    View Slide

  108. Let’s do it
    const AppNavigator = createStackNavigator({
    Home: { screen: MovieList },
    Movie: { screen: Movie },
    }, {
    navigationOptions: {
    headerTintColor: Colors.accent,
    headerStyle: Styles.header,
    }
    })
    const App = createAppContainer(AppNavigator)
    app/App.js
    export default class MovieList extends Component {
    static navigationOptions = {
    title: 'Movies',
    }
    //…
    app/components/MovieList.js
    data={this.state.movies}
    ListHeaderComponent={}
    keyExtractor={item => item.name}
    renderItem={({item}) =>
    underlayColor={Colors.subtleAccent}
    activeOpacity={0.5}
    onPress={() => navigate('Movie', {name: item.name})}
    >




    }
    />
    In render()

    View Slide

  109. Exercise
    Can you make a navigation transition from Movie to
    app/components/Actor ?
    Steps:
    - Declare the screen in app/App.js
    - Use a TouchableHighlight to capture onPress in the actors
    list of
    - Provide an appropriate title in
    - Make the actor displayed based on
    props.navigation.state.params.name
    Optional: have a look at
    https://reactnavigation.org/docs/en/stack-navigator.html
    And tweak the navigation (Ideas: mode modal, add something to headerRight)

    View Slide

  110. Networking

    View Slide

  111. Networking
    React-native uses the Fetch API
    If you already know it, you are all set

    View Slide

  112. Let’s do it
    componentDidMount() {
    return fetch(baseUrl + '/movies')
    .then((response) => response.json())
    .then((responseJson) => {
    this.setState({
    isLoading: false,
    movies: responseJson,
    })
    })
    .catch((error) => {
    console.error(error);
    })
    }
    app/components/MovieList.js

    View Slide

  113. Let’s do it
    git checkout networking
    yarn install
    yarn start-server
    (or npm run start-server)
    (To discard your changes)
    git reset HEAD --hard

    View Slide

  114. Further reading
    https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
    Docs:
    https://github.com/mzabriskie/axios
    Additional libraries:

    View Slide

  115. Interactive

    View Slide

  116. Our goal

    View Slide

  117. Working with state
    Not specific of React Native,
    we just use what we know of React

    View Slide

  118. Let’s do it
    git checkout interactive
    (To discard your changes)
    git reset HEAD --hard

    View Slide

  119. Modify the native side

    View Slide

  120. Cases where it is needed
    Installing packages that have a native side
    Making our own changes or components
    Installing assets, such as fonts

    View Slide

  121. Simple case
    Install this font

    View Slide

  122. Let’s do it
    module.exports = {
    project: {
    ios: {},
    android: {},
    },
    assets: ['./assets/fonts/'],
    };
    react-native.config.js
    git checkout mod-native
    (To discard your changes)
    git reset HEAD --hard

    View Slide

  123. Let’s do it
    module.exports = {
    project: {
    ios: {},
    android: {},
    },
    assets: ['./assets/fonts/'],
    };
    react-native.config.js
    npx react-native link
    git checkout mod-native
    (To discard your changes)
    git reset HEAD --hard

    View Slide

  124. Assets linked
    Changes to be committed:
    (use "git reset HEAD ..." to unstage)
    new file: android/app/src/main/assets/fonts/OleoScript-Bold.ttf
    new file: android/app/src/main/assets/fonts/OleoScript-Regular.ttf
    modified: ios/travolta.xcodeproj/project.pbxproj
    modified: ios/travolta/Info.plist
    modified: package.json

    View Slide

  125. Summary:
    What is React Native
    Starting a project
    Working with Styles
    Layout
    Lists
    Navigation
    Networking
    Touching the native side

    View Slide

  126. Thanks! @vicqr
    [email protected]

    View Slide