Build Mobile-Friendly Web Apps with React Native Web

Build Mobile-Friendly Web Apps with React Native Web

React Native is a multi-platform solution developed by Facebook that lets you build mobile apps using JavaScript. These mobile apps are considered multi-platform because they're written once and deployed across many platforms, like Android, iOS and the web.

React Native is a multi-platform solution developed by Facebook that lets you build mobile apps using JavaScript. These mobile apps are considered multi-platform because they're written once and deployed across many platforms, like Android, iOS and the web.

Over the years, building web applications that are mobile friendly has become easier with the advent of media queries and the introduction of service workers. Using media queries, we could make web applications that different shapes when viewed on mobile devices. Service workers, with their powerful features, present web applications with powers only native applications have been known to possess — push notifications, background sync, etc.

Table of Contents

React Native is a multi-platform solution developed by Facebook that lets you build mobile apps using JavaScript. These mobile apps are considered multi-platform because they’re written once and deployed across many platforms, like Android, iOS and the web. Today, we’ll see how we can utilize this powerful technology to build platform-focused applications on the web.

We’ll be building a simple application that displays user information from a random API using React Native components like ScrollView, Text and Image.

The library we’ll be using to build the demo is called React Native Web, "React Native for Web makes it possible to run React Native components and APIs on the web using React DOM”.

We’ll be building a simple application that will run both on the web and mobile using the React Native Web library, the application displays user information from a random API using React native components like ScrollView, Text, Image etc.

Prerequisites

To follow this tutorial, you’ll need to have Node > 6.0 installed. You’ll also need a package manager NPM (this comes packaged with Node) or Yarn(follow the installation guide here).

Basic knowledge of JavaScript and React is also required. You can follow the official React tutorial here to get up to speed with React.

Getting started

Before we get started, we’ll need to set up the project and install project dependencies. We’ll be making use of Create React App to bootstrap our application. We’re using Create React App because it can be configured to alias React Native. We’ll be installing polyfills for some of the latest JavaScript APIs like Promise, Array.from, etc., as the transpiler doesn’t provide those.

To bootstrap your application using Create React App, run the following command:

    yarn create react-app random-people
              or
    npx create-react-app random-people

Run the following command to install the project’s development dependencies:

    yarn add --dev babel-plugin-module-resolver babel-plugin-transform-object-rest-spread babel-plugin-transform-react-jsx-source babel-preset-expo
              or
    npm install --save-dev babel-plugin-module-resolver babel-plugin-transform-object-rest-spread babel-plugin-transform-react-jsx-source babel-preset-expo

The babel-plugin-module-resolver is a plugin that resolves your project modules when compiling with Babel. We’ll use this package to alias react-native to react-native-web when setting up the project config.

To build and run our application, we’ll be using Expo. Expo is an open-source toolchain built around React Native for building Android and iOS applications. It provides access to the system’s functionality like the Camera, Storage, etc.

Install the expo-cli by running the following command:

    yarn global add expo-cli
            or
    npm i g expo-cli

The next step is to install expo locally, alongside React Native and React Native Web. Run the command below to install the packages:

    yarn add expo react-native react-native-web react-art
            or
    npm i expo react-native react-native-web react-art

After downloading the packages needed to run and build the application, the next step is to setup the configuration files. Create a file called .babelrc in the root of your project and update it with the following:

    //.babelrc{
      "presets": ["babel-preset-expo"],
      "env": {
        "development": {
          "plugins": ["transform-object-rest-spread", "transform-react-jsx-source"]
        }
      },
      "plugins": [
        [
          "module-resolver",
          {
            "alias": {
              "^react-native$": "react-native-web"
            }
          }
        ]
      ]
    }

Create a file named app.json. This file is used to configure parts of your application that don’t belong in the code like the application name, description, sdkVersion, etc. You can find the options available for the app.json file here.

Let’s update the package.json file to include commands for running our application on Android and iOS emulators. Also, we’ll include the main field referencing the App.js file. This file will act as the entry file for the expo-cli. Open the package.json file in a file editor of choice:

    // package.json
    {
      "name": "random-people",
      "version": "0.1.0",
      "private": true,
      "main": "./App.js",
      ...
      "scripts": {
        "start-web": "react-scripts start",
        "build-web": "react-scripts build",
        "test-web": "react-scripts test",
        "eject-web": "react-scripts eject",
        "start-native" : "expo start",
        "android": "expo android",
        "ios": "expo ios",
        "build:ios": "expo build:ios",
        "build:android": "expo build:android",
      },
      ...
    }

Run npm run start-web to run the application and visit http://localhost:3000 to view the application.

Home component

Our application is a simple demo that displays users via the random user API. Using the API, we’ll get display a name and avatar of the returned users through some of the components provided by React Native. Within the src/ directory, create a file named home.js. Open this file using an editor and update it with the snippet below:

    //home.js
    import React from "react";
    import {
      ScrollView,
      ActivityIndicator,
      StyleSheet
    } from "react-native";

    class Home extends React.Component {
      state = {
        users: [],
        loading: true
      };
      componentDidMount() {
        // TODO: get users
      }

      render() {
        return (
          <ScrollView
            noSpacer={true}
            noScroll={true}
            style={styles.container}
          >
           <ActivityIndicator
                style={[styles.centering, styles.gray]}
                color="#ff8179"
                size="large"
              />
          </ScrollView>
        );
      }
    }

    var styles = StyleSheet.create({
      container: {
        backgroundColor: "whitesmoke"
      },
      centering: {
        alignItems: "center",
        justifyContent: "center",
        padding: 8,
        height: '100vh'
      },
    });

    export default Home;

In the snippet above, the Home component renders a ScrollView component that houses the component’s elements. Currently, the component displays an ActivityIndicator; this will be replaced by the user list when the call to the API is complete.

We create styles for the elements using the StyleSheet component. This allows us to style the component using properties similar to CSS properties.

Let’s create a method that gets random users from the Random User API. This method will be called during the componentDidMount lifecycle. Update the home.js component to include the getUsers method:

    // home.js
    import React from 'react';
    ...

    class Home extends React.Component {
      state = {
        ...
      };
      componentDidMount() {
        this.getUsers();
      }

      async getUsers() {
        const res = await fetch("https://randomuser.me/api/?results=20");
        const { results } = await res.json();
        this.setState({ users: [...results], loading: false });
      }
      ...
    }

We can easily make requests using the native Fetch API. Results from the request are parsed and added to state. When the request is complete, we’ll hide the ActivityIncidator by setting loading to false.

App component

The AppComponent holds the logic for the application. We’ll update the default view created by Create React App to suit that of our application by adding logic to display native components.

Create a new file named App.js in the root of your project. This file will be similar to the src/App.js file. The root App.js file will act as the entry file for expo, and the src/App.js file exists for Create React App builds. Update both files with the snippet below:

    import React from 'react';
    import {
      AppRegistry,
      StyleSheet,
      View,
    } from 'react-native';
    import Home from './home'

    class App extends React.Component {
      render() {
        return (
          <View style={styles.appContainer}>
            <Home />
          </View>
        );
      }
    }

    const styles = StyleSheet.create({
      appContainer: {
        flex: 1,
      },
    });

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

    export default App;

In the snippet above, we register our App component using the AppRegistry. The AppRegistry is the entry point of React Native applications.

Creating user item

Each user item will be displayed using a View component. The View component is an important building block that supports layout using flexbox, styling and accessibility. The View component of each item will be within a SwipeableFlatList. Each item will display the user’s avatar, name and email. Create a file called user-item.js within the src/ folder and update it with the code below:

    // user-item.js

    import React from "react";
    import { View, Image, Text, StyleSheet } from "react-native";

    const UserItem = ({ item: user }) => {
      return (
        <View style={styles.row}>
          <Image style={styles.rowIcon} source={user.picture.medium} />
          <View style={styles.rowData}>
            <Text style={styles.rowDataText}>{`${user.name.title} ${
              user.name.first
            } ${user.name.last}`}</Text>
            <Text style={styles.rowDataSubText}>{user.email}</Text>
          </View>
        </View>
      );
    };

    const styles = StyleSheet.create({
      row: {
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
        padding: 15,
        marginBottom: 5,
        backgroundColor: "white",
        borderBottomWidth: StyleSheet.hairlineWidth,
        borderBottomColor: "rgba(0,0,0,0.1)"
      },
      rowIcon: {
        width: 64,
        height: 64,
        marginRight: 20,
        borderRadius: "50%",
        boxShadow: "0 1px 2px 0 rgba(0,0,0,0.1)"
      },
      rowData: {
        flex: 1
      },
      rowDataText: {
        fontSize: 15,
        textTransform: "capitalize",
        color: "#4b4b4b"
      },
      rowDataSubText: {
        fontSize: 13,
        opacity: 0.8,
        color: "#a8a689",
        marginTop: 4
      }
    });

    export default UserItem;

To display the avatar of each user, we make use of the Image component. The component takes a source prop which acts the src which we are used to on the web. The component can be styled further as we have using styles.rowIcon property.

Next, we’ll create the UserList to display each UserItem.

Creating users list

The FlatList component is one that is performant in its list rendering methods. It lazy-loads the items within the list, and only loads more items when the user has scrolled to the bottom of the list. The SwipeableFlatList is a wrapper around the FlatList provided by React Native Web, which makes each item within the list swipeable — so each item will reveals a set of actions when swiped.

Let’s create the SwipeableFlatList for the users returned from the API. Import the SwipeableFlatList component from the react-native package and update the render function to display the list. Create a file called user-list.js and update the file with the following:

    import React from "react";
    import { SwipeableFlatList } from "react-native";
    import UserItem from "./user-item";

    const UserList = ({ users }) => {
      return (
        <SwipeableFlatList
          data={users}
          bounceFirstRowOnMount={true}
          maxSwipeDistance={160}
          renderItem={UserItem}
        />
      );
    };

    export default UserList;

Let’s update the home.js file to include the new UserList. Open the /src/home.js file and update it with the following:

    import React from "react";
    import { ScrollView, StyleSheet, ActivityIndicator } from "react-native";
    import UserList from "./user-list";

    class Home extends React.Component {
      state = {
        users: [],
        loading: true
      };
     ...
      render() {
        return (
          <ScrollView noSpacer={true} noScroll={true} style={styles.container}>
            {this.state.loading ? (
              <ActivityIndicator
                style={[styles.centering]}
                color="#ff8179"
                size="large"
              />
            ) : (
              <UserList users={this.state.users} />
            )}
          </ScrollView>
        );
      }
    }

    const styles = StyleSheet.create({
      ...
    });
    export default Home;

Now if you visit http://localhost:3000 on your browser, you should see a list of users, similar to the screenshot below:

If you can’t see users listed, go through the tutorial again to see what you’ve have missed along the way.

We’re using a SwipeableFlatList component which means each user item is swipeable, so let’s add actions that you can swipe to reveal. What’s the need of a SwipeableFlatList if it doesn’t reveal anything.

Adding actions to item

Each item within the list will be provided a set of actions that will be revealed when swiped to the left. The actions set will use the TouchableHighlight component encompassed by the View component. The TouchableHighlight component is used when we require viewers to respond to touches, more or less acting like a button. Create a file named user-actions.js in the src/ folder. Open the file and copy the following contents into it:

    import React from "react";
    import {
      View,
      TouchableHighlight,
      Text,
      Alert,
      StyleSheet
    } from "react-native";

    const styles = StyleSheet.create({
      actionsContainer: {
        flex: 1,
        flexDirection: "row",
        justifyContent: "flex-end",
        alignItems: "center",
        padding: 10
      },
      actionButton: {
        padding: 10,
        color: "white",
        borderRadius: 6,
        width: 80,
        backgroundColor: "#808080",
        marginRight: 5,
        marginLeft: 5
      },
      actionButtonDestructive: {
        backgroundColor: "#ff4b21"
      },
      actionButtonText: {
        textAlign: "center"
      }
    });

    const UserActions = () => {
      return (
        <View style={styles.actionsContainer}>
          <TouchableHighlight
            style={styles.actionButton}
            onPress={() => {
              Alert.alert("Tips", "You could do something with this edit action!");
            }}
          >
            <Text style={styles.actionButtonText}>Edit</Text>
          </TouchableHighlight>
          <TouchableHighlight
            style={[styles.actionButton, styles.actionButtonDestructive]}
            onPress={() => {
              Alert.alert(
                "Tips",
                "You could do something with this remove action!"
              );
            }}
          >
            <Text style={styles.actionButtonText}>Remove</Text>
          </TouchableHighlight>
        </View>
      );
    };

    export default UserActions;

The TouchableHighlight component takes an onPress callback that is triggered when the component is clicked. Each callback triggers an Alert display. Styles are also applied to the encompassing View component and other components on the page.

To include the actions on each user item, update the UserList component to include the renderQuickActions prop, which also takes a function.

    import React from "react";
    ...
    import UserActions from "./user-actions";

    const UserList = ({ users }) => {
      return (
        <SwipeableFlatList
          ...
          renderQuickActions={UserActions}
        />
      );
    };

    export default UserList;

Now when you swipe left on any user item it reveals two actions. It should be similar to the screenshot below:

Header component

Now that we’ve successfully fetched users and displayed them using native components, let’s liven the application by setting a header. Using the SafeAreaView component, we’ll create an area with defined boundaries. This will act as the header for our application. Create file called header.js and update it with the code below:

    // src/header.js
    import React from 'react';
    import {SafeAreaView, View, Text, StyleSheet} from 'react-native';

    const Header = ({ onBack, title }) => (
      <SafeAreaView style={styles.headerContainer}>
        <View style={styles.header}>
          <View style={styles.headerCenter}>
            <Text accessibilityRole="heading" aria-level="3" style={styles.title}>{title}</Text>
          </View>
        </View>
      </SafeAreaView>
    );

    const styles = StyleSheet.create({
      headerContainer: {
        borderBottomWidth: StyleSheet.hairlineWidth,
        borderBottomColor: '#ff4e3f',
        backgroundColor: '#ff8179',
      },
      header: {
        padding: 10,
        paddingVertical: 5,
        alignItems: 'center',
        flexDirection: 'row',
        minHeight: 50
      },
      headerCenter: {
        flex: 1,
        order: 2
      },
      headerLeft: {
        order: 1,
        width: 80
      },
      headerRight: {
        order: 3,
        width: 80
      },
      title: {
        fontSize: 19,
        fontWeight: '600',
        textAlign: 'center',
        color: 'white'
      },
    });

    export default Header;

Now let’s add the Header component to the App component. This will display a simple header at the top of the application. Update the App.js file to include the Header component:

    import React from 'react';
    ...
    import Header from './header';

    class App extends React.Component {
      render() {
        return (
          <View style={styles.appContainer}>
            <Header title="Random People" />
            <Home />
          </View>
        );
      }
    }

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

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

    export default App;

After the application refreshes the header will be added to the top of the application.

Looks great, doesn’t it? It won’t be winning any awards, but it might win a lot of prospective react-native-web users. We’ve been able to achieve a lot of functionality after writing minimal code.

Let’s see the various methods we can use to test the application on mobile.

Testing on mobile

To test the application on mobile, the expo-cli provides various method to test the application mobile. The first is using a URL generated after running the application, this URL can be visited on your mobile browser to test the application.

To test the application on mobile, the expo-cli provides various method to test the application mobile. The first is using a URL generated after running the application. This URL can be visited on your mobile browser to test the application.

Run the npm run start-native command within your project folder to run the application using expo. Expo typically starts your application on port 19002, so visit http://localhost:19002 to view the expo dev tools. Within the dev tools you can send a link as an SMS or email to your mobile phone.

You can select any of the three connection options — an external tunnel, LAN or Local connection. For the local connection, your mobile phone and work PC have to be connected to the same network, but the tunnel works regardless.

The next option for testing on a mobile device is using a emulator. Using Android studio or Xcode, you can boot emulators for their respective platforms. Download and install the tool for the platform of choice — Xcode for iOS or Android studio for Android. After installation, run npm run android or npm run ios to start the application on any of the emulators.

Deploying the application

We’ll be deploying our application to the Android Play store. To achieve this, we’ll need to update the app.json to include Android specific properties. Open the app.json file and update the file to include the android field:

    {
      "expo": {
        "sdkVersion": "31.0.0",
        "name": "random-people",
        "slug": "random-people",
        "version": "0.1.0",
        "description": "An application for displaying random people",
        "primaryColor": "#ff8179",
        "android": {
          "package": "com.random.people"
        }
      }
    }

The android.package field is a unique value that will represent your package in the app store. You can read more on the package-naming convention here. After updating the file, run the npm run build:android command.

This command will present you with a prompt, asking you to provide a keystore or to generate a new one. If you have an existing keystore, you can select this option or let expo generate one for your application.

After completion, a download link will be generated for your application. Clicking on this link will trigger a download for your APK.

To deploy the downloaded APKto the Android Play Store, visit the Play Console to create an account. After creating an account, you’ll be required to pay a registration fee of $25 before proceeding. After completing the registration process, visit this page and follow the steps to upload your application to the Play Store.

Summary

Using the React Native Web and React Native libraries, we’ve been able to create an application that can be deployed on several platforms using native components. Building multi-platform applications has never been easier. You can view the source code for the demo here.

React Native Web Tutorial - Build Workout App for iOS, Android and Web

React Native Web Tutorial - Build Workout App for iOS, Android and Web

React Native Web Full App Tutorial - Build a Workout App for iOS, Android, and Web. Learn to use React Native for Web to create a workout app that works on Android, iOS, and the web. The app uses Mobx, Typescript, React Navigation, React Hooks, AsyncStorage / Localstorage, and more. Once the app is complete, you will learn how to deploy it to Netlify.

React Native Web Full App Tutorial - Build a Workout App for iOS, Android, and Web

Learn to use React Native for Web to create a workout app that works on Android, iOS, and the web.

The app uses Mobx, Typescript, React Navigation, React Hooks, AsyncStorage / Localstorage, and more. Once the app is complete, you will learn how to deploy it to Netlify.

💻 Code: https://github.com/benawad/react-native-web-series

⭐️ Contents ⭐️
⌨️ (0:00:00) Setting Up a React Native Web Project
⌨️ (0:09:04) Setting Up React Native Hooks
⌨️ (0:15:03) Setting Up a React Native Web Monorepo
⌨️ (0:28:24) Configuring React Native for Yarn Workspaces
⌨️ (0:39:58) How to use Mobx with React Hooks
⌨️ (0:49:15) Navigation in React Native Web
⌨️ (1:03:28) Styling a Component in React Native Web
⌨️ (1:27:40) Mobx Root Store
⌨️ (1:45:20) Workout Timer with Mobx
⌨️ (2:11:20) React Router with React Native Web
⌨️ (2:22:45) How to Persist Mobx Stores
⌨️ (2:30:47) Storing and Displaying Workout History
⌨️ (2:54:33) React Router Params in React Native Web
⌨️ (3:17:30) Floating Action Button React Native Web
⌨️ (3:34:45) Deploy React Native Web to Netlify

React Native Web Full App Tutorial - Build a Workout App for iOS, Android, and Web

React Native Web Full App Tutorial - Build a Workout App for iOS, Android, and Web

React Native Web Full App Tutorial - Build a Workout App for iOS, Android, and Web. Learn to use React Native for Web to create a workout app that works on Android, iOS, and the web. The app uses Mobx, Typescript, React Navigation, React Hooks, AsyncStorage / Localstorage, and more. Once the app is complete, you will learn how to deploy it to Netlify.

Learn to use React Native for Web - Build a Workout App for iOS, Android, and Web

Learn to use React Native for Web to create a workout app that works on Android, iOS, and the web. The app uses Mobx, Typescript, React Navigation, React Hooks, AsyncStorage / Localstorage, and more. Once the app is complete, you will learn how to deploy it to Netlify.

💻 Code: https://github.com/benawad/react-native-web-series

⭐️ Contents ⭐️
⌨️ (0:00:00) Setting Up a React Native Web Project
⌨️ (0:09:04) Setting Up React Native Hooks
⌨️ (0:15:03) Setting Up a React Native Web Monorepo
⌨️ (0:28:24) Configuring React Native for Yarn Workspaces
⌨️ (0:39:58) How to use Mobx with React Hooks
⌨️ (0:49:15) Navigation in React Native Web
⌨️ (1:03:28) Styling a Component in React Native Web
⌨️ (1:27:40) Mobx Root Store
⌨️ (1:45:20) Workout Timer with Mobx
⌨️ (2:11:20) React Router with React Native Web
⌨️ (2:22:45) How to Persist Mobx Stores
⌨️ (2:30:47) Storing and Displaying Workout History
⌨️ (2:54:33) React Router Params in React Native Web
⌨️ (3:17:30) Floating Action Button React Native Web
⌨️ (3:34:45) Deploy React Native Web to Netlify

React Native Tutorial - Build Android and iOS App from Scratch

React Native Tutorial - Build Android and iOS App from Scratch

React Native Tutorial - Build Android and iOS App from Scratch. Getting started tutorial on building an Android and iOS app from scratch using React Native. React Native is a modern Javascript framework backed by Facebook that use to make Mobile Apps (Android/iOS) development easier for Javascript developer. In other words, React Native is React.js mobile apps development version.

A comprehensive step by step tutorial on building Android and iOS app from scratch using React Native

A comprehensive getting started tutorial on building an Android and iOS app from scratch using React Native. React Native is a modern Javascript framework backed by Facebook that use to make Mobile Apps (Android/iOS) development easier for Javascript developer. In other words, React Native is React.js mobile apps development version. For more information about React Native definition, features, etc, you can find in their official documentation.

Shortcut to the steps:

  • Install React App Creator and Create A React Native App
  • Add Navigation Header and Home Screen
  • Load World Cup 2018 Data from API
  • Display List of World Cup Matchdays
  • Display World Cup 2018 Matchdays Details
  • Run the React Native World Cup 2018 App

In this React Native tutorial, we are creating an app that listing the World Cup 2018 matches using the free open public domain football data for the world cups in the JSON format.

The following tools, frameworks, and modules are required for this tutorial:

  • React Native
  • Node.js (NPM or Yarn)
  • Worldcup JSON data
  • Android Studio or SDK for Android
  • XCode for iOS
  • Terminal (OSX/Linux) or Command Line (Windows)
  • Text Editor or IDE (We are using Atom)

Before start to the main steps, make sure that you have installed Node.js and can run npm in the terminal or command line. To check existing or installed Node.js environment open the terminal/command line then type this command.

node -v
v8.11.1
npm -v
6.1.0
yarn -v
1.7.0

That's the Node and NPM or YARN version that we are using. In this tutorial, we will use Yarn commonly.

Install React App Creator and Create A React Native App

The Create React Native App is a tool for creating a React Native App. To install it, type this command in your App projects folder.

sudo npm install -g create-react-native-app

Then create a React Native App using this command.

create-react-native-app reactWorldCupApp

That command will create a React Native app then install all required modules. The app or project folder will contain these folders and files.

Next, go to the newly created React App folder.

cd reactWorldCupApp

This React Native App is running via Expo app, before running on your Android or iOS device, make sure you have to install the Expo App to Android or Expo Client to iOS. Of course, that app is available in the App Store. So, we assume that you have installed the Expo App in your device then type this command to run the app.

npm start

or

yarn start

You will see this barcode and instruction in the terminal or command line.

To open the app in the Android device, open the Expo App first then tap on Scan QR Code button. Scan the barcode in the terminal or command line then you will see the React Native Android App like this after waiting for minutes the build process.

For iOS Device, press s from the keyboard to send React Native App URL to your Email or SMS. Enter your phone number or Email address (We use an email address) then press Enter. You will get this email to your mailbox.

Choose open in Expo URL then open in your browser, that will be redirected to Expo App. In Expo App welcome screen, shake your phone to open the React Native App. Now, you will see this screen in your iOS device.

This step for development purpose, we will show you how to build for production at the end of this article.

Add Navigation Header and Home Screen

Above generated React Native App just show blank app with plain text. Now, we will show you how to add the Navigation Header and Home Screen for your app. So, it will look like the Native App. In the terminal or command line type this command to install React Navigation (react-navigation) module.

yarn add react-navigation

Next, create a folder for components and React Native components files in the root of the app folder.

mkdir components
touch components/HomeScreen.js
touch components/DetailsScreen.js

Open and edit components/HomeScreen.js then add this React Native codes.

import React, { Component } from 'react';
import { Button, View, Text } from 'react-native';

class HomeScreen extends Component {
  static navigationOptions = {
    title: 'Home',
  };
  render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Home Screen</Text>
        <Button
          title="Go to Details"
          onPress={() => this.props.navigation.navigate('Details')}
        />
      </View>
    );
  }
}

export default HomeScreen;

Open and edit components/DetailsScreen.js then add this React Native codes.

import React, { Component } from 'react';
import { Button, View, Text } from 'react-native';

class DetailsScreen extends Component {
  static navigationOptions = {
    title: 'Details',
  };
  render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Details Screen</Text>
        <Button
          title="Go to Details... again"
          onPress={() => this.props.navigation.push('Details')}
        />
        <Button
          title="Go to Home"
          onPress={() => this.props.navigation.navigate('Home')}
        />
        <Button
          title="Go back"
          onPress={() => this.props.navigation.goBack()}
        />
      </View>
    );
  }
}

export default DetailsScreen;

Next, open and edit App.js then add replace all codes with this.

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { createStackNavigator } from 'react-navigation';
import HomeScreen from './components/HomeScreen';
import DetailsScreen from './components/DetailsScreen';

const RootStack = createStackNavigator(
  {
    Home: HomeScreen,
    Details: DetailsScreen,
  },
  {
    initialRouteName: 'Home',
    navigationOptions: {
      headerStyle: {
        backgroundColor: '#f4511e',
      },
      headerTintColor: '#fff',
      headerTitleStyle: {
        fontWeight: 'bold',
      },
    },
  },
);

export default class App extends React.Component {
  render() {
    return <RootStack />;
  }
}

When the files are saved, the Expo app will refresh the React Native App automatically. Now, the app will look like this.

Load World Cup 2018 Data from API

To load World Cup 2018 data from API, open and edit components/HomeScreen.js then add constructor function before rendering function.

constructor(props){
  super(props);
  this.state ={ isLoading: true}
}

Add function for load API JSON data which the JSON response set to the dataSource.

componentDidMount(){
  return fetch('https://raw.githubusercontent.com/openfootball/world-cup.json/master/2018/worldcup.json')
    .then((response) => response.json())
    .then((responseJson) => {
      // console.log(responseJson);
      this.setState({
        isLoading: false,
        dataSource: responseJson.rounds,
      }, function(){

      });

    })
    .catch((error) =>{
      console.error(error);
    });
}

The response from API holds by dataSource variable that will use in the view in the next step.

Display List of World Cup Matchdays

We will use the List and ListItem component of React Native Elements (react-native-elements) module. First, install react-native-elements using this command.

yarn add react-native-elements

Open and edit again components/HomeScreen.js then replace all imports with these imports of React, Component (react), StyleSheet, ScrollView, ActivityIndicator, Text, View (react-native), List, and ListItem (react-native-elements).

import React, { Component } from 'react';
import { StyleSheet, ScrollView, ActivityIndicator, Text, View  } from 'react-native';
import { List, ListItem } from 'react-native-elements';

Next, replace all render function with this React Native rendered template which the ActivityIndicator load only if the state status is loading. The list that gets from the data source displaying to the ListItem after mapping the array of the data source.

render() {
  if(this.state.isLoading){
    return(
      <View style={styles.activity}>
        <ActivityIndicator/>
      </View>
    )
  }

  return(
    <ScrollView style={styles.container}>
      <List>
        {
          this.state.dataSource.map((item, i) => (
            <ListItem
              key={i}
              title={item.name}
              leftIcon={{name: 'soccer-ball-o', type: 'font-awesome'}}
              onPress={() => {
                this.props.navigation.navigate('Details', {
                  matches: `${JSON.stringify(item.matches)}`,
                });
              }}
            />
          ))
        }
      </List>
    </ScrollView>
  );
}

Add style const before the export code.

const styles = StyleSheet.create({
  container: {
   flex: 1,
   paddingBottom: 22
  },
  item: {
    padding: 10,
    fontSize: 18,
    height: 44,
  },
  activity: {
    flex: 1,
    padding: 20,
  }
})
Display World Cup 2018 Matchdays Details

We will display World Cup 2018 Matchdays Details in the DetailsScreen. Open and edit components/DetailsScreen.js then replace all imports with this.

import React, { Component } from 'react';
import { StyleSheet, ScrollView, View } from 'react-native';
import { List, ListItem, Text, Card } from 'react-native-elements';

Next, replace all render function with these lines codes.

render() {
  const { navigation } = this.props;
  const matches = JSON.parse(navigation.getParam('matches', 'No matches found'));
  console.log(matches);

  return (
    <ScrollView>
      <Card style={styles.container}>
        {
          matches.map((item, key) => (
            <View key={key} style={styles.subContainer}>
              if(item.group) {
                <View>
                  <Text h3>{item.group}</Text>
                </View>
              }
              <View>
                <Text h3>{item.team1.name} vs {item.team2.name}</Text>
              </View>
              <View>
                <Text h5>{item.date}</Text>
              </View>
              <View>
                <Text h4>{item.score1} - {item.score2}</Text>
              </View>
              if(item.goals1.length > 0) {
                item.goals1.map((item2, key2) => (
                  <View key={key2}>
                    <Text h4>{item2.name} ({item2.minute})</Text>
                  </View>
                ))
              }
              if(item.goals2.length > 0) {
                item.goals2.map((item3, key3) => (
                  <View key={key3}>
                    <Text h5>{item3.name} ({item3.minute})</Text>
                  </View>
                ))
              }
            </View>
          ))
        }
      </Card>
    </ScrollView>
  );
}

Add StyleSheet const before the export code.

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20
  },
  subContainer: {
    flex: 1,
    paddingBottom: 20,
    borderBottomWidth: 2,
    borderBottomColor: '#CCCCCC',
  }
})
Run the React Native World Cup 2018 App

To run the application in Expo App, you can find in step 1 of this article. If there's no error found, you will see the result like this.


Next, to run or build as the Native App, type this command to install React Native CLI first.

sudo npm install -g react-native-cli

Next, eject the project from the Create React Native App by type this command.

npm run eject

You will get questions like below, make it the same with the one that we choose.

? How would you like to eject from create-react-native-app? React Native: I'd like a regular React Native project.
We have a couple of questions to ask you about how you'd like to name your app:
? What should your app appear as on a user's home screen? React World Cup
? What should your Android Studio and Xcode projects be called? ReactWorldCupApp

Next, to run the Native iOS or Android App in the Simulator, type this command.

react-native run-ios
react-native run-android

That it's for now. Any suggestions are open for next React Native tutorial. You can find the full working source code in our GitHub.