React Native Tutorial: Building Android Apps with JavaScript

In this React Native tutorial you’ll learn how to build native apps based on the hugely popular React JavaScript library, with a focus on Android. By Christine Abernathy.

Leave a rating/review
Save for later
Share
You are currently viewing page 2 of 5 of this article. Click here to view the first page.

React Native Basics

In this section, you’ll learn React Native basics as you begin working on PropertyFinder.

Open App.js in your text editor of choice and take a look at the structure of the code in the file:

import React, { Component } from 'react'; // 1
import {Platform, StyleSheet, Text, View} from 'react-native';

const instructions = Platform.select({ ... }); // 2

type Props = {};
export default class App extends Component<Props> { ... } // 3

const styles = StyleSheet.create({ ... }); // 4

Let’s go through the code step-by-step:

  1. Imports the required modules.
  2. Sets up a platform-specific display message.
  3. Defines the component that represents the UI.
  4. Creates a style object that controls the component’s layout and appearance.

Take a closer look at this import statement:

import React, { Component } from 'react';

This uses the ECMAScript 6 (ES6) import syntax to load the react module and assign it to a variable called React. This is roughly equivalent to importing libraries in Android. It also uses what’s called a destructuring assignment to bring in the Component object. Destructuring lets you extract multiple object properties and assign them to variables using a single statement.

Note: For more information about ES6 modules I’d recommend reading this blog post by Dr. Axel Rauschmayer.

ES6 is a much nicer way to write JavaScript, supporting features like default parameters, classes, arrow functions, and destructuring assignments. Not all browsers support ES6. React Native uses a tool called Babel to automatically translate modern JavaScript into compatible legacy JavaScript where necessary.

Back to App.js, check out the class definition:

export default class App extends Component<Props>

This defines a class which extends a React Component. The export default class modifier makes the class “public”, allowing it to be used in other files.

Open index.js and take a look at the entry point file:

import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';

AppRegistry.registerComponent(appName, () => App);

This registers the imported component that serves as the app’s entry point.

It’s time to start building your app.

In App.js, add the following at the top of the file, just before the import statements:

'use strict';

This enables Strict Mode, which adds improved error handling and disables some less-than-ideal JavaScript language features. In simple terms, it makes JavaScript better!

Inside the App class replace render() with the following:

render() {
  return React.createElement(Text, {style: styles.description}, "Search for houses to buy!");
}

App extends React.Component, the basic building block of the React UI. Components contain immutable properties, mutable state variables and expose a method for rendering. Your current application is quite simple and only requires a render method.

React Native components are not Android view classes; instead they are a lightweight equivalent. The framework takes care of transforming the tree of React components into the required native UI.

Next, replace the const styles statement with the following:

const styles = StyleSheet.create({
  description: {
    fontSize: 18,
    textAlign: 'center',
    color: '#656565',
    marginTop: 65,
  },
});

This defines a single style that you’ve applied to the description text. If you’ve done any web development before, you’ll probably recognize those property names. The React Native StyleSheet class used to style the application UI is similar to the Cascading Style Sheets (CSS) used on the Web.

Then, get rid of the instructions assignment code block as you no longer need it.

Save your changes to App.js and return to the emulator. Double tap R on your keyboard, and you’ll see your fledgling property search app starting to take shape:

That’s a JavaScript application running in the emulator, rendering a native UI, without a browser in sight!

Still don’t trust me? :] Verify it for yourself: within Android Studio, select Tools\Android\Layout Inspector. Then check Show All Proceses, select com.propertyfinder and tap OK to inspect the view hierarchy:

You will see no WebView instances anywhere! Your text is being displayed in a view called ReactTextView:

But what is that? Go to the project file finder and enter ReactTextView.java in the prompt. Select the result matching this file to view the source code. Notice ReactTextView inherits directly from TextView. Neat!

Curious as to how it all works? Take a quick look at MainActivity.java and MainApplication.java which you can find in android/app/src/main/java/com/propertyfinder.

MainApplication sets up a ReactNativeHost which in turn creates a ReactInstanceManager. The instance manager handles the communication between JavaScript and native Android.

MainActivity extends ReactActivity which creates a ReactRootView when launched. ReactRootView uses the instance manager to start the JavaScript application. It also renders the App component to set the Activity’s content view.

The terminal window that was opened when you ran this application started a packager and server that allows your JavaScript code to be fetched, by default on port 8081. For example:

http://localhost:8081/index.bundle?platform=android

Open this URL in your browser; you’ll see the JavaScript code for your app. You can find your “Search for houses to buy!” description code embedded among the React Native framework.

When your app starts, this code is loaded and executed by the JavaScriptCore library. In the case of your application, it loads the App component, then constructs the native Android view.

Using JSX

Your current application uses React.createElement to construct the simple UI for your application, which React turns into the native equivalent. While your JavaScript code is perfectly readable in its present form, a more complex UI with nested elements would rapidly become quite a mess.

Make sure the app is still running, then return to your text editor to edit App.js. Modify the body of render to be the following:

return <Text style={styles.description}>Search for houses to buy! (Again)</Text>;

This is JSX, or JavaScript syntax extension, which mixes HTML-like syntax directly in your JavaScript code; if you’re already a web developer, this should feel rather familiar. You’ll use JSX throughout this article.

Save your changes to App.js and return to the emulator. Tap R twice, and you’ll see your application refresh to display the updated message:

Re-running a React Native application is really as simple as refreshing a web browser! :] Note that this will only reflect changes made to your JavaScript files – native code or resource changes will require you to restart the packager.

You can even skip having to refresh the app by enabling live reload. Press Cmd+m for Mac or Ctrl+m for Windows/Linux in the emulator then select Enable Live Reload:

In App.js, modify the render method’s body to the following:

return <Text style={styles.description}>Search for houses to buy!</Text>;

Save your changes. Note that the emulator automatically refreshes to reflect your changes:

Christine Abernathy

Contributors

Christine Abernathy

Author

Joe Howard

Final Pass Editor

Over 300 content creators. Join our team.