Getting Started with React Native

Weather App

In this chapter we’re going to build a weather application that allows the user to search for any city and view its current forecast.

With this simple app we’ll cover some essentials of React Native including:

  • Using core and custom components
  • Passing data between components
  • Handling component state
  • Handling user input
  • Applying styles to components
  • Fetching data from a remote API

By the time we're finished with this chapter, you'll know how to get started with Create React Native App and build a basic application with local state management. You’ll have the foundation you need to build a wide variety of your own React Native apps.

Here’s a screenshot of what our app will look like when it’s done:

The completed app

In this chapter, we'll build an entire React Native application from scratch. We'll talk about how to set up our development environment and how to initialize a new React Native application. We'll also learn how Expo allows us to rapidly prototype and preview our application on our mobile device. After covering some of the basics of React Native, we'll explore how we compose apps using components. Components are a powerful paradigm for organizing views and managing dynamic data.

We're about to touch on a wide variety of topics, like styling and data management. This chapter will exhibit how all these topics fit together at a high-level. In subsequent chapters, we'll dive deep into the concepts that we touch on here.

Code examples

This book is example-driven. Each chapter is setup as a hands-on tutorial.

We'll be building apps from the ground up. Included with this book is a download that contains completed versions of each app as well as each of the versions we develop along the way (the "sample code.") If you're following along, we recommend you use the sample code for copying and pasting longer examples or debugging unexpected errors. If you're not following along, you can refer to the sample code for more context around a given code example.

The structure of the sample code for all the chapters in this book follows this pattern:


├── components/
├── App.js
├── 1/
│   ├── components/
│   └── App.js
├── 2/
│   ├── components/
│   └── App.js
├── 3/
│   ├── components/
│   └── App.js
// ...

At the top-level of the directory is App.js and components/. This is the code for the completed version of the application. Inside the numbered folders (1/, 2/, 3/) are the different versions of the app as we build it up throughout the chapter.

Here's what a code example in this book looks like:


  render() {
    return (
      <View style={styles.container}>
        <Text>Open up App.js to start working on your app!</Text>
        <Text>Changes you make will automatically reload.</Text>
        <Text>Shake your phone to open the developer menu.</Text>
      </View>
    );
  }

Note that the title of the code block contains the path within the sample code where you can find this example (weather/1/App.js).

JavaScript

This book assumes some JavaScript knowledge.

React Native uses Babel as a JavaScript compiler to allow us to develop in the latest version of JavaScript, ES2016. To understand what we mean by JavaScript versions, you can refer to the Appendix.

We highlight some of JavaScript's newer features in the Appendix. We reference the appendix when relevant.

Starting the project

Create React Native App

To begin, we're going to use Create React Native App (CRNA), a tool that makes it extremely easy to get started with React Native. If you've used Create React App before, you'll notice similarities here in that no build configuration is required to get up and running. We can install it globally using yarn.

yarn

yarn is a node package manager that automates the process of managing all the required dependencies and packages from npm, an online repository of published JavaScript libraries and projects, in an application. This is done by defining all our dependencies in a single package.json file.

npm also has a command line tool, npm, that allows us to maintain and control dependencies. The tool that we use to build our application, CRNA, does not currently work with the latest version of npm, npm v5. For this reason, we'll use yarn throughout the book.

You can refer to the documentation for instructions to install yarn for your operating system. The documentation also explains how to install node as well. In order to use CRNA however, Node.js v6 or later is required.

Here's a list of some commonly used yarn commands:

  • yarn init creates a package.json file and adds it directly to our project.
  • yarn installs all the dependencies listed in package.json into a local node_modules folder.
  • yarn add new-package will install a specific package to our project as well as include it as a dependency in package.json. Dependencies are packages needed when we run our code.
  • yarn add new-package --dev will install a specific package to our project as well as include it as a development dependency in package.json. Development dependencies are packages needed only during the development workflow. They are not needed for running our application in production.
  • yarn global add new-package will install the package globally, rather than locally to a specific project. This is useful when we need to use a command line tool anywhere on our machine.

If we already have an older version of npm than v5 installed, we can use it instead of yarn and run its equivalent commands.

Watchman

Watchman is a file watching service that watches files and triggers actions when they are modified. If you use macOS as your operating system, the Expo and React Native documentation recommend installing Watchman for better performance. The instructions to install the service can be found here.

Expo

Expo is a platform that provides a number of different tools to build fully functional React Native applications without having to write native code. Beginning a project with CRNA automatically creates an application that leverages Expo's development environment.

A benefit of leveraging Expo is that building an application does not require using Xcode for iOS, or Android Studio for Android. This means that developers can build native iOS applications without even owning a Mac computer. Using CRNA and Expo is the easiest way to get started with React Native and is recommended in the React Native documentation.

Including Native Code

Using Expo and CRNA isn't the only way to start a React Native application. If we need to start a project with the ability to include native code, we'll need to use the React Native CLI instead. With this however, our application will require Xcode and Android Studio for iOS and Android respectively.

Expo also provides a number of different APIs for device specific properties such as contacts, camera and video. However, if we need to include a native iOS or Android dependency that is not provided by Expo, we'll need to eject from the platform entirely. Ejecting an Expo application means we have full control of managing our native dependencies, but we would need to use the React Native CLI from that point on.

We'll explore how to add native modules onto a React Native project later on this book.

Previewing the app

To develop and preview apps with Expo, we need to install its client iOS or Android app to develop and run React Native apps on our device.

Android

On your Android mobile device, install the Expo Client on Google Play. You can then select Scan QR code and scan this QR code once you've installed the app:


QR Code

If this QR code doesn't work, we recommend making sure you have the latest version of that Expo app installed, and that you're reading the latest edition of this book.

Instead of scanning the QR code, you can also type the project URL, exp://exp.host/@fullstackio/weather, inside of Expo to load the application.

iOS

You can install the Expo Client via the App Store. With an iOS device however, there is no capability to scan a QR code. This means we'll first need to build the final app in order to preview it. We can do this by navigating to the weather/ directory in the sample code folder and running the following commands:


cd weather
yarn
yarn start

This will start the React Native packager. Pressing s will allow you to send a link to your device by SMS or e-mail (you'll need to provide your mobile phone number of email address). Once done, clicking the link will open the application in the Expo Client.

For the app to load on your physical device, you'll need to make sure that your phone is connected to the same local network as your computer.

Local Development Tool

In addition to a client app, Expo also provides two local development tools that allow us to preview, share and publish our projects:

  • XDE, or the Expo Development Environment, is a desktop app that we can use for macOS, Windows, or Linux.
  • exp is a command line interface.

Both options provide a number of different commands and services that we can use to manage our applications. Instead of using the s hotkey provided by CRNA when we start the packager to send the link to an iOS device, we can also use exp or XDE instead.

We'll explore using these local development tools in more detail when we cover deploying and publishing apps later in this book.

Preparing the app

At this point, you should see the final application load successfully on your device. Play around with the app for a few minutes to get a feel for it. Try searching for different cities as well a location that doesn't even exist.

If you plan on building the application as you read through the chapter, you'll need to create a brand new project. Once yarn is installed, let's run the following command to install Create React Native App (CRNA) globally:


yarn global add [email protected]

The @1.0.0 specifies the version of create-react-native-app to install. It's important to lock in version 1.0.0 so that the version on your machine matches that here in the book.

We'll call our application weather and can use the following command to get started (this command may take a little while):


create-react-native-app weather --scripts-version 1.14.0

Importantly, we specify the --scripts-version as 1.14.0. We'll talk about this in a moment.

We'll then navigate to that directory and boot the app:


cd weather
yarn start

With the pacakger running, we can continue to scan the QR code with an Android device or send a link directly to our iOS device using the s hotkey. It is important to remember that our device needs to be connected to the same local network as our computer in order for this to work.

Right now, viewing the app shows our starting point:

Application

Running on a simulator

As we mentioned, using the Expo client app allows us to run our application without using native tooling (Xcode for iOS, or Android Studio for Android).

However if we happen to have the required build tools we can still run our application in a virtual device or simulator:

  • With a Mac, yarn run ios will start the development server and run the application in an iOS simulator. We can also start the packager separately with yarn start and press i to open the simulator.
  • With the required Android tools, yarn run android will start the application in an Android emulator. Similarly, pressing a when the React Native packager is running will also boot up the emulator.

Running an application using an emulator/simulator can be useful to test on different devices and screen sizes. It can also be quicker to update and test code changes on a virtual device. However, it's important to run your application on an actual device at some point in order to get a better idea of how exactly it looks and feels.

By default, CRNA comes with live reload enabled. This means if you edit and save any file, the application on your mobile device will automatically reload. Moreover, any build errors and logs will be displayed directly in the terminal.

Let's see what the directory structure of our app looks like. Open up a new terminal window.

Navigate to this app:


cd weather

And then run ls -a to see all the contents of the directory:


ls -a

If you're using PowerShell or another non-Unix shell, you can just run ls.

Although your output will look slightly different based on your operating system, you should see all the files in your directory listed:


├── node_modules/
├── .babelrc
├── .flowconfig
├── .gitignore
├── .watchmanconfig
├── App.js
├── app.json
├── App.test.js
├── package.json
├── README.md
└── yarn.lock

Let's go through each of these files:

  • node_modules/ contains all third party packages in our application. Any new dependencies and development dependencies go here.
  • .babelrc allows us to define presets and plugins for configuring Babel. As we mentioned previously, Babel is a transpiler that compiles newer experimental JavaScript into older versions so that it stays compatible with different platforms.
  • .flowconfig allows us to configure Flow, a static type checker for JavaScript. Flow is part of the React Native toolchain and this file is included automatically in any React Native application. We won't be using Flow in this chapter but we will explore prop validations briefly using prop-types.
  • .gitignore is where we specify which files should be ignored by Git. We can see that both the node_modules/ and .expo/ directories are already included.
  • .watchmanconfig defines configurations for Watchman.
  • App.js is where our application code lives.
  • app.json is a configuration file that allows us to add information about our Expo app. The list of properties that can be included in this file is listed in the documentation.
  • App.test.js is included as a sample test file and contains a single test. CRNA is packaged with Jest as its testing platform. We'll go into detail about unit testing React Native applications in the "Testing" chapter.
  • package.json is where we provide information of the application to our package manager as well as specify all our project dependencies.
  • README.md is a markdown file commonly used to provide a description of a project.
  • yarn.lock is where yarn keeps a record of the versions of each dependency installed.