What is React Redux used for?

React Native: Entry into the development of mobile apps

Prof. Dr. Erik Behrends March 20, 2018

If you want to develop an app for smartphones, there are numerous different approaches available. So you have to z. For example, decide whether a mobile web application is sufficient or whether a native app is required for special functions. The open-source framework React Native makes it possible to program native apps across platforms and in parallel for Android and iOS in JavaScript. By programming a simple game, this article shows how to get started with app development with React Native.

The React Native framework, presented by Facebook as an open source project in 2015, impresses with many advantageous properties. The parallel development of high-performance, native apps on a code base for Android, iOS and other target platforms with many useful tools that ensure high productivity are particularly noteworthy [1]. Therefore, React Native with more than 60,000 stars is one of the most popular projects on GitHub [2] and many well-known companies such as B. Airbnb and Tesla use the framework to develop their apps [3].

A memory training game

You are going to develop a simple game that will train your short term memory. As can be seen in Fig. 1, the app consists of three colored squares that are arranged one below the other. At the very bottom there is a button that you can use to start the game. After the game has started, one of the three squares flashes five times in a row in a random order. Then you must reproduce this exact order by pressing the appropriate squares in order to win a game round.

Preparation: Develop apps in the browser

In order to develop a mobile app with React Native, nothing needs to be installed on the computer - a web browser is sufficient. Expo Snack is a service on the web that provides a programming environment for React Native directly in the browser. As Fig. 01 shows, the source text of the app is edited in an editor area and to the right of it, a preview shows the app either in a virtual Android device or in an iPhone. The preview can be activated with the control button Preview can be activated in the footer. If you want, you can try the game online right away. It can be used in the browser at Expo Snack [4].

However, because the preview of the app takes up some space in the browser and is sometimes only started after a certain waiting time, I recommend using the app Expo [5], which you can get free of charge for Android or iOS in the respective AppStore [6]. A search for Expo Client in the AppStore also leads you to this app.

Expo Snack generates a unique QR code for an app, which can be accessed with the help of the QR code can be displayed in the browser. In the Expo app on the smartphone there is a function with which this QR code can be scanned so that the app is loaded directly onto the mobile phone and executed there. Expo Snack and the Expo app are examples of the excellent tools in the React Native environment. With Expo Snack in particular, programming with React Native can be started immediately.

Of course, React Native also provides a comprehensive development environment that can be set up on your own computer. However, since this takes a lot of time, you will find the information on this at the end of the article. Now we're going to start programming the app!

First steps with Expo Snack

I will now describe the necessary development steps for the sample app. If you enter the code fragments listed in the browser in Expo Snack, you will already get a first impression of how React Native is programmed.

For this article I have provided the starting point of the program code in Expo Snack [7]. If you navigate to Expo Snack in the browser, you will first see a QR code for the app shown. If you have installed the Expo app on your smartphone, you can scan the QR code there to run the app on your mobile phone. Otherwise, you can close the displayed QR code and preview the app in the browser using the switch Preview open at the bottom of the website. I also recommend using the file view (Files) and the component list (Components) with the corresponding switches in the footer, so that you have more space for the editor. If you want to use the preview of the app in the browser, you may have to wait a while before the preview starts.

If you want to change your code now and save it temporarily, you can press the button Save changes to press. Note, however, that you will then be given a new URL each time. If you want to reload the app on your smartphone with Expo, you can shake the device briefly back and forth so that a menu with useful functions appears. Please also note that when you enter the code in the editor, errors can occur in the app in the meantime, as Expo Snack executes the program code immediately with every change. A red screen then appears in the app with the error message. Do not let this confuse you, because if the entered source text is finally correct, the app will also display as expected.

A simple component

Now we come to the code of the app prepared for you. The content of the file is in the editor area App.js to see. A simple component is declared there. For an app developed with React Native and Expo is App.js the entry point and the component it contains is displayed when the app is opened.

The following listing contains the program code in App.jsas it is contained in the editor of Expo Snack in the browser:

import React, {Component} from 'react'; import {View, StyleSheet} from 'react-native'; export default class App extends Component {render () {return ( ); }} const styles = StyleSheet.create ({container: {flex: 1, alignItems: 'center', justifyContent: 'center',}, box: {backgroundColor: 'red', width: 150, height: 150}}) ;

The code consists of three sections, each separated by a blank line:

  1. import- instructions for required APIs and components,
  2. Definition of your own component as a class (class) and
  3. Declaration of styles for the representation and layout of the component

When you program an app with React Native, it essentially means implementing your own components and using them together with other components. Modern JavaScript language concepts are often used here, which were introduced with ECMAScript 2015 (ES 2015) and later versions. This can be seen here, for example. B. at the importStatements and the class definition with class. Each component of its own is usually classified as a subclass of Component is declared and at least the method render implement, which in turn uses an expression return that declaratively describes the UI. In the case of this component, this is the following fragment:

<View style={styles.container}> <View style={styles.box} /> </View>

This is markup declared in a syntax called JSX. JSX is reminiscent of HTML or XML, but is translated into JavaScript before the program code is executed. Here contains an exterior ViewElement one more View-Component. In React Native corresponds to View in about one div in HTML - a block element with no special appearance. The two ViewElements each have a style-Attribute that refers to summarized styling properties.

Styling in React Native

There is an API in React Native called StyleSheet, which facilitates the declaration of styles. This API is imported at the beginning of the code along with the other required components and APIs. Styles are also defined in JavaScript, although there is a certain similarity to CSS. In principle, styles are objects that consist of properties, which in turn contain any styling instructions. For example, in the property Container three instructions summarized:

container: {flex: 1, alignItems: 'center', justifyContent: 'center',},

With flex: 1 the component will assume a maximum expansion. Its content is analogous to the flexbox layout from the CSS specification based on justifyContent: 'center' centered along the main vertical axis and additionally perpendicular to this axis (through alignItems: 'center'). The View-Component identified by the styles in styles.box is displayed as a red square, therefore appears in the center of the screen.

By specifying the styles in the file in which the component is also declared, the component is self-describing and enables it to be reused, since the complete information for its representation (render and styles) is summarized in one place. This is one of the advantages of component-based programming that React Native receives from the underlying React web library.

Show three squares and a button

In the next step, add two more squares to the app and place one at the bottom of the screen Button The following listing contains the necessary changes:

import React, {Component} from 'react'; import {Button, View, StyleSheet} from 'react-native'; export default class App extends Component {render () {return (

Simple variant of the game with state (state)

At any point in time, the game or the app can be in exactly one of the following states, which can be achieved through certain processes:

  1. No game is active (the app was started before or a game has just ended).
  2. A game is active (the button below was tapped) and a list of colors has been specified.
  3. The user taps the wrong square in the order to be reproduced, which ends the game.
  4. The user taps the correct square in that order. The current number in the sequence is saved for the next time you tap a square.

So there are three properties that can change their state in the game:

  1. game - game is active (true) or not (false),
  2. colorList - a list (Array) of colors that the user must select in exactly this order, e.g. B. ['blue', 'red', 'green'] and
  3. pressed - a number with a value of 0 to colorList.length - 1, which stands for the last square you tapped.

In React Native, components can store their state in an object called state manage. If this object changes, the method is automatically used render so that the UI updates. The initial state of a component can be changed with state be declared at the beginning of the class. Complete the class App with a corresponding assignment:

export default class App extends Component {state = {game: false, colorList: [], pressed: 0}; // the rest remains unchanged ...

The app starts in such a way that no game is active, no colors have been specified and no square has yet been tapped. If the user taps the button at the bottom of the screen, a new game begins. So adjust the ButtonComponent in such a way that when you tap a method _newGame is performed:

<Button title="Neues Spiel" onPress={() => this._newGame()} />

It is a React Native convention to start the names of custom methods that are not part of the framework with an underscore. Declare this method inside the class e.g. B. before render as follows:

_newGame () {if (this.state.game) return; const theColors = ['blue', 'red', 'green']; this.setState ({game: true, colorList: theColors, pressed: 0}); }

If the property this.state.game the value true the method ends prematurely by the return-Instruction, because a game is already active. Otherwise, the constant is given for the first easy variant of the game (still without random colors) theColors three colors in the order of the three squares from top to bottom. This is followed by a call to this.setState, a method React Native provides to change the state of the component. Here we activate the game (game: true), assign the (not yet) random colors to the color list (colorList: theColors) and initialize the counter for the last tapped square (pressed: 0).

Now add the following method _checkColor the class App added (e.g. below _newGame):

_checkColor (color) {const {game, pressed, colorList} = this.state; if (! game) return; if (colorList [pressed]! == color) {alert ('Unfortunately you lost!'); this.setState ({game: false}); } else if (pressed === colorList.length - 1) {alert ('Great, you won!'); this.setState ({game: false}); } else {this.setState ({pressed: pressed + 1}); }}

The code in _checkColor reads the current state through destructive assignments in constants that are named like the state properties ({game, pressed, colorList}). If no game is currently active, the method ends with return. In the case of an active game, there are three different situations:

  1. The wrong square was tapped - this leads to a corresponding message and to the end of the game.
  2. The correct square was tapped and it is the last one in the sequence - a suitable hint appears that the user has won and the game is over.
  3. The correct square was tapped and the current counter turns over 1 increased (in this case a game is active and we have not yet reached the end of the sequence).

Now adjust the method render so that tapping (onPress) of a square the method _checkColor with the associated color value:

render () {return ( this._checkColor ('blue')}> this._checkColor (' red ')}> this._checkColor ('green')}> < Button title = "New Game" onPress = {() => this._newGame ()} /> ); }

You can now test the game, even if the order of the colors is always the same: blue, red and then green.

The step-by-step changes to the program code included: two new methods and therefore the following listing represents the complete component App after the adjustments just made:

import React, {Component} from 'react'; import {Button, TouchableOpacity, View, StyleSheet} from 'react-native'; export default class App extends Component {state = {game: false, colorList: [], pressed: 0}; _newGame () {if (this.state.game) return; const theColors = ['blue', 'red', 'green']; this.setState ({game: true, colorList: theColors, pressed: 0}); } _checkColor (color) {const {game, pressed, colorList} = this.state; if (! game) return; if (colorList [pressed]! == color) {alert ('Unfortunately you lost!'); this.setState ({game: false}); } else if (pressed === colorList.length - 1) {alert ('Great, you won!'); this.setState ({game: false}); } else {this.setState ({pressed: pressed + 1}); }} render () {return ( this._checkColor ('blue')}> this._checkColor ('red')}> this._checkColor ('green')}>