amp
Nov 05 2018 02:53pm | | Share

React Native Mobile App with AWS Amplify

By Shu Zhang

A mobile app I’m working on is using full-fledged serverless services provided by Amazon Web Services (AWS). I’m using them with React Native to run the app on both Android and iOS platforms with one code base.

 

We needed a way to connect AWS to our mobile app. To start we used ‘aws-sdk’, an AWS SDK library, but later we switched to use the AWS Amplify library for its simplicity. So far, the library supports a handful of services, such as Analytics, Storage, Authentication, Notifications and so on. It also provides very powerful toolchain called Amplify CLI to help developers manage backends, host websites and generate client code.

 

Let’s see how to use AWS Amplify and React Native to build a simple app.

 

First, make sure your development environment has all the required tools in compatible versions. Node.js version is at least 8.11 and npm version is 5.x or greater. Also make sure you have access to an AWS account. If you don’t already have AWS account, you can sign up a 12 months account with free tier access here: https://portal.aws.amazon.com/billing/signup?redirect_url=https%3A%2F%2Faws.amazon.com%2Fregistration-confirmation#/start

 

The second step is to create a React Native app. To make things simple, here I’m using Expo CLI to create the mobile app. All we need to do is type in command npm install -g expo-cli to install Expo CLI and create a directory for the app. Run command expo init in the directory and answer questions to create a project.

 

Go to the project folder and run command expo start to make sure the app is created successfully. Follow the instructions on the screen and change content of file ‘screens/HomeScreen.js’ by adding a <Text> component. You should be able to see content change from the left screen to something like this.

 

gg

 

Now we’re ready to add the Amplify library to the app.

 

First, we need to install Amplify CLI using this command: npm install -g @aws-amplify/cli. And then run amplify configure to setup access to your AWS account. You need to answer the questions and it’ll open a browser to login to your AWS account.

 

After these are done, you can add Amplify to the React Native app you just created using these commands: 

npm install --save aws-amplify,

npm install --save aws-amplify-react-native,

react-native link.

 

dd

 

Now we can use Amplify CLI to create new AWS resources and pull the AWS services configuration into the app. In the app directory, type in command amplify init, and answer the questions in the following screen.

 

img

 

You can run amplify in the terminal to see a list of available services.

Here we’re adding analytics to the app with the command amplify add analytics.

 

img

 

And then run amplify push to create the backend resource.

 

img

 

The most important step is of course, to add analytics related code to ‘./App.js’ file.


 

import React from 'react';

import { StyleSheet, View, Linking, Text, Button } from 'react-native';

import Auth from'@aws-amplify/auth';

import Analytics from'@aws-amplify/analytics';

import awsconfig from'./aws-exports';

 

//retrieve temporary AWS credentials and sign requests

Auth.configure(awsconfig);

Analytics.configure(awsconfig);

 

export default class App extends React.Component {

  constructor(props){

    super(props);

    this.state = {

      resultHtml: <Text></Text>,

      eventsSent: 0

    };

    this.handleAnalyticsClick = this.handleAnalyticsClick.bind(this);

  }

//send analytics events to Amazon Pinpoint

  handleAnalyticsClick() {

    Analytics.record('AWS Amplify Demo')

      .then((evt) => {

        const url = 'https://console.aws.amazon.com/pinpoint/home/?region=us-east-1#/apps/'

                    + awsconfig.aws_mobile_analytics_app_id 

                    + '/analytics/events';

//Display result in text indicating event has been submitted.

        const result = (

          <View>

            <Text>Event submitted.</Text>

            <Text>Events sent: { ++this.state.eventsSent }</Text>

            <Text style={styles.link} onPress={() => Linking.openURL(url)}>

              View events on Amazon Pinpoint console

            </Text>

          </View>

        );

 

        this.setState({

          'resultHtml': result

        });

      });

  }

//render home screen content

  render() {

    return (

      <View style={styles.container}>

        <Text>Welcome to my demo app!</Text>

        <Button title="Generate Analytics Event" onPress={this.handleAnalyticsClick} />

        {this.state.resultHtml}

      </View>

    );

  }

}

 

const styles = StyleSheet.create({

  container: {

    flex: 1,

    backgroundColor: '#fff',

    alignItems: 'center',

    justifyContent: 'center'

  },

  link: {

    color: 'blue'

  }

});

 

 

Now you can build and rerun your app. You’ll see a ‘GENERATE ANALYTICS EVENT’ button on the home screen. After you tap on the button, you should see text indicating that the event has been submitted. Tapping multiple times will increase the number of events sent to the backend. Wait a few minutes before going back to the AWS Pinpoint console to checkout data updates. You should see some graphs similar to these screenshots.

 

img       img  

 

Generally speaking, you should find Amplify library much easier to use than ‘aws-sdk’ library. As they point out on the aws-amplify wiki page, “Amplify should be a manifestation of The Rule of Least Power when developing against AWS”. However, there are some services that haven’t been supported by Amplify yet. So, you might still need to use the ‘aws-sdk’ library occasionally.