Tyler Knapp

Getting Started with React Native

October 25, 2019

Made it to Mod 5!

This post was also featured on Medium:

Congratulations on making it to Mod 5! You’re almost there. From the conversations I had at the Mod 5 science fair, I felt that I could pass on some value and save you some time in getting started with React Native. The following post will go over what I learned, libraries I used, and hopefully some advice that will help you hit the ground running.

Wireframes & Designs

The best place to start with any project is with wireframes and designs. Wireframes and designs are vital to creating a great User Experience. By spending time up front fleshing out your user experience such as your sign up flow, auth flow, etc. you will work out the kinks without any programming.

Once you have laid out the blueprint of your app, screens, components, and flows, then all you have to do is figure out how to implement it. There are some great tools to help you get started.

Tools for wireframing + design :

  • *Photoshop
  • InVision
  • Sketch
  • *Marvel — this is a prototyping app that links static images together giving you something that you can actually interact with and simulate on your phone through their mobile app. Here is what I created on Marvel for my app
  • Figma
  • *Draw.io — it is recommended that you draw out your component trees for your pitch to the instructors

*The tools I used in the process of designing and prototyping my app. I urge you to spend some time using these before you jump into programming.

Snack

If you aren’t sold on React Native yet, visit Snack. Snack is an in-browser code-editor + simulator. You can browse their examples and preview some of the behaviors unique to React Native. Do not be afraid of the in-file StyleSheet or vs.

tags! I will get to the differences and similarities in React Native later in this post.

Xcode

If you are set on React Native let’s get started by downloading some tools. Head over to Apple and download Xcode. We will not be working within Xcode unless there is some native functionality that your project needs and that React Native or Expo does not provide. We will need Xcode primarily for its built in simulator which will allow us to test our app locally. We will need cocoapods which manage library dependencies for Xcode projects so navigate to your root directory then enter the following command in your terminal:

sudo gem install cocoapods

Yarn

I also recommend using Yarn which is a package manager that replaces the existing workflow for the npm client or other package managers while remaining compatible with the npm registry. It has the same feature set as existing workflows while operating faster, more securely, and more reliably.

brew install yarn

Expo

While those are downloading open another terminal and enter the following command to download Expo. In the meantime, you can create an account on expo.io. You do not need a paid account.

npm install expo-cli — global

Expo is an open source framework built around React Native which helps you quickly get an app up and running on your local environment. Expo to React Native is similar to what Rails is to Ruby. It provides a set of tools that simplify the development and testing of React Native app and arms you with the proven components and services that you would typically find through third-party libraries. Expo also provides a lot of React Native components that can access native functionality. Once Xcode and Expo have been installed on your machine, you can navigate to your preferred directory and enter the following command to generate an Expo starter.

expo init example

You’ll be hit with a couple of prompts. My preference in learning is to build it myself while following along with the docs, so for this example I am going to recommend using the Managed Workflow — Blank preset.

Then enter a name for your project (make sure you fill out both fields — you can navigate to the next field using the tab button)

First Expo Prompt

When prompted to use yarn to install your dependancies, enter yes.

First Expo Prompt

Finally, navigate to your project directory and run the following:

cd example
sudo xcode-select -s /Applications/Xcode.app
yarn start

If you have everything downloaded from above:

First Expo Prompt

  1. Your terminal will prompt you for which device to run the app on
  2. A localhost webpage should open in browser prompting you for the same.

The sudo xcode commands ensures your project directory is connected to the simulator

In your terminal enter i for the iOS simulator. This will open the simulator app + download Expo onto the simulator.

You’re up and running!

First Expo Prompt

React Native

If you are confident in React, you will be confident in React Native. Mod 4 covers just about everything you need to know for the basics of building a small app with React Native. The general philosophy is the same. The following will highlight some differences:

  1. WE ARE NOT WORKING WITH JSX(HTML)

    React Native does not manipulate HTML. Instead, we are given built-in components that act similar to the JSX we have been working with in React. Here are a couple you need to know:

The following components will need to be imported from ‘react-native’ like so:

import { View, Text, TextInput, etc. } from 'react-native'

View similar to what div’s are in react and we will be using these as containers for other components

Text will replace elements that render text(p, h1, h2, etc.)

TextInput’s are just that, field inputs.

StyleSheet will be added directly to your screen/container/component files and will be your stand in for css

ScrollView provides the scrolling functionality for components rendered within it.

SafeAreaView If your screen does not scroll, I would recommend wrapping your components with SafeAreaView

Image

TouchableOpacity

Button Styling with buttons can be difficult, if you would like to create custom buttons I would point you to Handlebar Labs tutorial and repo(you will create a custom button component that you can use throughout your app): https://www.youtube.com/watch?v=UUcaqUUeHWE

Please spend some time reading through the docs linked for those components so you can see the subtle differences such as with Images. With React Native if you are rendering an image asset from you project directory, you will need a require statement, if you are rendering an image from an external source, your Image source props will be equal to an object containing a uri link.

  1. Your terminal can act as your Console

    What is React Native? At its core, React Native is Javascript. This means you can still console.log as much as your heart desires. Expo provides an in-browser debugger, which, like every other webpage, you can ‘inspect’ and open the console to see everything that’s been logged from your app. To turn the Debug Remote JS on press ⌘d in the simulator app and select Debug Remote JS. I personally found the terminal to be the most convenient option. Whichever terminal shell you run yarn start in, will also act as the console. “Hello, Terminal” was from a console.log in the render method of app.js.

First Expo Prompt

  1. ⌘r forces the app to refresh
  2. PATIENCE Your app will break early and often. Do not get frustrated with yourself and do not give up. Expo provides great feedback on what’s causing the issue. Take your time and read through the errors.
  3. Push your repo up often This is something I did not do as often as I should have. As soon as you implement a new feature, push it up. If you need to backtrack, this will save you a tremendous amount of time.
  4. Screens < Containers < Components Screens should be the Parent component. Within screens you can render your containers or components.
  5. STYLING — No classnames, instead object references If you noticed from the Snack example or the Expo project we just started up, there are no classNames. Instead, at the bottom of the screen you will see a StyleSheet object being created. I followed this convention throughout my app.
const styles = StyleSheet.create({
    container: {
     flex: 1,
     backgroundColor: '#fff',
     alignItems: 'center',
     justifyContent: 'center',
    },
   });

Another similarity you might notice is the naming convention of the attribute you would like to modify. In CSS, to change the background color you would do something like this:

container {
   background-color: #fff;
}

Because we are now creating a Javascript object, we need to use something similar to what we would use with in-line styling in React:

<View style={styles.container}>
  <Text>Hello, World</Text>
</View>
...
const styles = StyleSheet.create({
    container: {
     backgroundColor: '#fff',
    },
   });

Another thing to note, unless the value is an Integer, you will most likely be passing strings, ALSO no px’s:

const styles = StyleSheet.create({
    container: {
     backgroundColor: '#fff',
     height: '100%',
     fontSize: 10
    },
   });
  1. Event Listeners

TextInputs accept an onChangeText, not onChange.

Throw yourself into it

Let’s jump right into it and create a signup form. In the Expo example we just created head into the app.js file.

Refactor app.js to a class component (and replace starter content with Sign Up!)

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
class App extends React.Component {
  render(){
   return (
    <View style={styles.container}>
      <Text>Sign Up!</Text>
    </View>
   );
  }
}
export default App
const styles = StyleSheet.create({
   container: {
     flex: 1,
     backgroundColor: '#e6e6e6',
     alignItems: 'center',
     justifyContent: 'center',
  }
});
  1. Add state for our TextInput fields
state = {
   email: '',
   name: '',
   password: ''
}
  1. import SafeAreaView, TextInput, Button from ‘react-native’

*OPTIONAL — import lodash(great library for making clones)

import {  StyleSheet, Text, View, SafeAreaView, TextInput, Button } from 'react-native';
import _ from 'lodash'
  1. Refactor View to be SafeAreaView
  2. Create a formContainer
<SafeAreaView style={styles.container}>
  <Text>Sign Up!</Text>
    <View style={styles.formContainer}>
    </View>
</SafeAreaView>
  1. Create the fields
<View style={styles.formContainer}>
  <TextInput placeholder="Email" />
  <TextInput placeholder="Name" />
  <TextInput placeholder="Password" />
</View>
  1. Add submit button within formContainer
<View style={styles.formContainer}>
  <TextInput placeholder="Email" />
  <TextInput placeholder="Name" />
  <TextInput placeholder="Password" />
  <Button title="Submit" onPress={this.handleSubmit}/>
</View>
  1. For each input, create an inline onChangeText(No computed property names in React Native i.e. [e.target.name] = e.target.value)
<TextInput placeholder="Email" onChangeText={email => this.setState({ email })} />
<TextInput placeholder="Name" onChangeText={name => this.setState({ name })} />
<TextInput placeholder="Password" onChangeText={password => this.setState({ password })} />
  1. Create a handleSubmit within the class component
handleSubmit = () => {
  if (this.state.email && this.state.name && this.state.password){
   const user = _.clone(this.state)
   console.log(user)
  }
}
  1. Add some style and React Native TextInput Magic!
import React from 'react';
import {  StyleSheet, Text, View, SafeAreaView, TextInput, Button } from 'react-native';
import _ from 'lodash'
class App extends React.Component {
state = {
   email: '',
   name: '',
   password: ''
 }

handleSubmit = () => {
 if (this.state.email && this.state.name && this.state.password){
 const user = _.clone(this.state)
 console.log(user)
  }
}
render(){
return (
  <SafeAreaView style={styles.container}>
   <Text>Sign Up!</Text>
    <View style={styles.formContainer}>
<TextInput placeholder="Email" onChangeText={email => this.setState({ email })} style={styles.input} autoCapitalize="none" />
<TextInput placeholder="Name" onChangeText={name => this.setState({ name })} style={styles.input} autoCapitalize="none" />
<TextInput placeholder="Password" onChangeText={password => this.setState({ password })} style={styles.input} secureTextEntry/>
   <Button title="Submit" onPress={this.handleSubmit}/>
  </View>
 </SafeAreaView>
  );}
}
export default App
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#e6e6e6',
    alignItems: 'center',
    justifyContent: 'center',
  },
    formContainer: {
    alignItems: 'center',
    width: '100%'
 },
  input: {
    backgroundColor: 'white',
    padding: 10,
    margin: 10,
    width: "80%"
  }
});
  1. You now have a sign up form you can dispatch actions from!

Quick Sign Up Form

Link to full post on Medium


Tyler

Tyler is a recent graduate of Flatiron School's immersive software engineering program in New York City. You should check him out on Github.