What is React Native?

React Native claims to be a library for building user-interfaces. If that statement seems a little vague it’s because the library is designed to be used on various devices, platforms, operating systems, etc.

Written in JavaScript—rendered with native code.

reactnative.dev

The library allows developers to write applications, or inject code into an existing application, that utilizes features from Javascript and React. This decreases the skill barrier between a web developer that uses the React framework and a developer wanting to get into mobile development.  That means that if you know React, you can use many of your preexisting skills to become a mobile developer at a faster rate.

React Native is typically used for mobile devices running iOS or Android. However, there is also support for TV devices that support Apple TV and Android TV.

A good way to help you understand React Native is to compare iit with ReactJS.

What are the differences Between React Native and ReactJS?

ReactJS is—also—a framework for building user interfaces. React Native and ReactJS both use:

  • props
  • state
  • components
  • JSX

If you’re new to React you should start with this article on using React and APIs. Furthermore, you can explore the ReactJS documentation.

The key difference between React Native and ReactJS is that React Native is rendered with native code (not always HTML). It’s common to use many <div>, <h1>, and <p> HTML elements when building a ReactJS web application. However, in React Native these become elements like <View> and <Text>. The React Native documentation has a helpful chart for comparing these components.

https://reactnative.dev/docs/intro-react-native-components#core-components

Above, you can see the different React Native elements and their corresponding web equivalents. In our example application, we are going to use a few of these core components to help get you comfortable with the new component names.

One aspect of ReactJS and React Native that remains very similar is how you call external APIs from the application.

REST API CALLS

Applications on the web and mobile devices often cannot store all the information that they need. Therefore, they have to reach out to the web to update data, retrieve data, or request a service from a third-party. The transaction that takes place between two devices (client and server) is called an API call. An API (application programming interface) typically will use the REST design paradigm to manage all the ways that it can be accessed (called).

Since this has become a very common task for applications to do, a few helpful ways have emerged to get this done. In this article, we are going to talk about the fetch function and the axios library. Both of these methods achieve the same task, making an HTTP call, but they go about it in slightly different ways.

Fetch

The fetch API is a built-in Javascript function. You can use fetch by providing the URL for the location of your content. This will send a GET request to that URL.

fetch('https://example.com/data');

Depending on what is at that address, a response object will be returned with the data. The data is not returned instantaneously. Therefore, the fetch API returns a Promise. The Promise object will return a response object when the network request is done. We can string together functions that will execute when the Promise returns a response object.

fetch('https://example.com/data').then((response) => response.json()).then((json) => {
    return data.names;
}).catch((error) => {
    console.error(error);
});

We can read through the above code like;

  1. Fetch the data at the URL 'https://example.com/data'
  2. Then, transform the response into JSON
  3. Then, return the names property on the JSON object
  4. If there is an error, log the error to the console.

The fetch function is versatile in regard to the types of HTTP requests that it can send. We can provide more parameters to send a POST request.

fetch('https://example.com/data', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    newName: 'Some Name',
    id: 123
  })
});

We provided four parameters to the fetch function in the example above.

  1. URL
  2. Request method
  3. HTTP headers
  4. Data

This is a simple way to start sending HTTP requests as soon as possible. However, another popular method for sending HTTP requests is with third-party libraries.

One of the top libraries that developers use is Axios.

Axios

The Axios library has grown in popularity alongside the increase in apps that exchange information using JSON. Three things that make the Axios library so useful are the ability to;

  • Intercept requests and responses
  • Transform request and response data
  • Automatically transform data for JSON
import Axios from 'axios'

Axios({
  url: '/data',
  method: 'get',
  baseURL: 'https://example.com',
  transformRequest: [function (data, headers) {
    // Do whatever you want to transform the data
 
    return data;
  }],
  transformResponse: [function (data) {
    // Do whatever you want to transform the data
 
    return data;
  }],
  headers: {'X-Requested-With': 'XMLHttpRequest'},
  data: {
    name: 'Some Name'
  },
})

In the above example, we have passed a configuration object that calls an example URL with a GET request. You’ll notice that some of the parameter names are common between fetch and Axios.

Next, let’s take a look at a smaller GET request.

axios.get('https://example.com/data')
  .then(function (response) {
    return response.names;
  })
  .catch(function (error) {
    console.log(error);
  })

We are calling the same URL as we did with the fetch API, but we don’t have to manually transform the response object into JSON. Axios has more features that can be useful with bigger applications, but we are going to focus on the basics in our React Native application.

How to make REST API Calls in React Native App

View the code on Github

Prerequisites

  1. Node 12 LTS or greater installed
  2. Internet connection
  3. Smartphone
  4. Basic understanding of React
  5. Ability to open and execute commands on a command line or terminal application.

1. Setting Up the Project

Expo

Open up a new terminal command-line and download the Expo CLI.

npm install -g expo-cli

Use your terminal/command shell to navigate to the folder that you wish to create the project in. Once you are in the directory, enter the command;

expo init ReactNativeApiCall

The shell will prompt you for details on how you want to set up the project.

Select the blank template in the Managed Workflow section of the CLI options.

Next, change directories in ReactNativeApiCall and start the app by running expo start.

After starting the development server, you need to download the Expo Client App on your smartphone.

Then, depending on your smartphone operating system, use the QR-Code to view the app on your smartphone:

  • iOS users can open the Camera app and point it at the QR-code
  • Android users will need to use the Expo app to scan the QR-code

Running expo start should open up a browser that allows you to interact with Expo and your app.  I had to change the connection to “Tunnel”, so the app would load properly on my phone when scanning the QR-code.

The Javascript bundle compiled on my phone and I am now able to view my app.

Next, we can make some edits to App.js to see how our app updates.

App.js

Open up a code editor that allows you to see the project files in ReactNativeApiCalls.

First, change the text in the Text component to “Example with fetch and Axios”. Then, add another Text component above that component with the code;

<Text style={styles.title}>Native API Calls</Text>
Notice that we added a style attribute and assigned it a value from the styles object that is declared at the bottom of the file. However, this style doesn’t exist yet. Add the title property to the styles object.
..
  title: {
    fontSize: 35,
    color: '#fff'
  }
..

Save App.js. The development server should update the application on your phone to reflect the changes that we made in the file. Your app should now look like the image below.

2. Subscribe to the API

To add an API call, you need to have an account on RapidAPI.

Sign Up For a Free Account on RapidAPI

Visit RapidAPI to get signed up if you haven’t already!

Subscribe to the Quotes API

Next, visit the dashboard for the Quotes API. Click the Subscribe to Test button that takes you to the Pricing tab.

On the Pricing page, you can view an API’s pricing and subscribe to one of the plans that the API offers. This API is free and only has one plan. Notice that I have already subscribed so I have a link to Manage and View Usage.

Now that we have subscribed, we are able to use the API in our application.

3. Call API with fetch

First, add the following function at the top of the App component in App.js.

..  
  const fetchApiCall = () => {
    fetch("https://quotes15.p.rapidapi.com/quotes/random/?language_code=en", {
      "method": "GET",
      "headers": {
        "x-rapidapi-host": "quotes15.p.rapidapi.com",
        "x-rapidapi-key": "yourapikey"
      }
    })
      .then(response => response.json())
      .then(response => {
        console.log(response.content);
        console.log(response.originator.name)
      })
      .catch(err => {
        console.log(err);
      });
  }
..

Be sure to replace the value for "x-rapidapi-key" with your API key from RapidAPI. Hard coding your API key into the application, in this way, does not secure the value. Someone else could find the key if you published the app or pushed the code to a repository. For a more in-depth look at React Native, and how to secure an API key in React Native, check out this tutorial.

Next, import the TouchableHighlight component from React Native at the top of the file.

import { StyleSheet, Text, View, TouchableHighlight } from 'react-native';
Then, add a new component underneath the last Text component.
 .... 
     <TouchableHighlight onPress={fetchApiCall}>
        <View style={styles.button}>
          <Text style={styles.buttonText}>Use Fetch API</Text>
        </View>
      </TouchableHighlight>
....

This component calls the Quotes API with our fetch function when pressed.

Next, add the button and buttonText styles to the styles object before saving the file and refreshing the app.

button: {
  padding: 10,
  marginVertical: 15,
  backgroundColor: '#0645AD'
},
buttonText: {
  color: '#fff'
}

Save the file, and press the button that we now have in our app. A quote and source should be logged to the console in the browser and in the terminal.

Finally, let’s add some variables to App.js so we can display the text information when it’s available.

At the top of the App component, add two variables using React hooks.

export default function App() {
  let [quote, setQuote] = React.useState('')
  let [source, setSource] = React.useState('')

Then, in the fetchApiCall function change the code where we are logging the quote values to the code below.

....
      .then(response => {
        setQuote(response.content);
        setSource(response.originator.name)
      })
....

Save and refresh the app.

Clicking the button now fetches the data and displays the quoted text and source in the app.

The code in App.js should now be:

import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View, TouchableHighlight } from 'react-native';

export default function App() {
  let [quote, setQuote] = React.useState('')
  let [source, setSource] = React.useState('')

  const fetchApiCall = () => {
    fetch("https://quotes15.p.rapidapi.com/quotes/random/?language_code=en", {
      "method": "GET",
      "headers": {
        "x-rapidapi-host": "quotes15.p.rapidapi.com",
        "x-rapidapi-key": "yourapikey"
      }
    })
      .then(response => response.json())
      .then(response => {
        setQuote(response.content);
        setSource(response.originator.name)
      })
      .catch(err => {
        console.log(err);
      });
  }

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Native API Calls</Text>
      <Text>Example with fetch and Axios</Text>
      <TouchableHighlight onPress={fetchApiCall}>
        <View style={styles.button}>
          <Text style={styles.buttonText}>Use Fetch API</Text>
        </View>
      </TouchableHighlight>
      <View>
        <Text>{quote}</Text>
        <Text>{source}</Text>
      </View>
      <StatusBar style="auto" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#AAA',
    alignItems: 'center',
    justifyContent: 'center',
    color: '#fff'
  },
  title: {
    fontSize: 35,
    color: '#fff'
  },
  button: {
    padding: 10,
    marginVertical: 15,
    backgroundColor: '#0645AD'
  },
  buttonText: {
    color: '#fff'
  }
});

4. Call API with Axios

Let’s implement the same functionality, but with Axios. To use Axios we need to install it with NPM. Open up a terminal in the root of our project directory (ReactNativeApiCalls). Run the command npm install axios.

Next, import Axios at the top of App.js.

import axios from 'axios'

Then add this function below the fetchApiCall function;

const axiosApiCall = () => {
  axios({
    "method": "GET",
    "url": "https://quotes15.p.rapidapi.com/quotes/random/",
    "headers": {
      "content-type": "application/octet-stream",
      "x-rapidapi-host": "quotes15.p.rapidapi.com",
      "x-rapidapi-key": "yourapikey",
      "useQueryString": true
    }, "params": {
      "language_code": "en"
    }
  })
    .then((response) => {
      setQuote(response.data.content);
      setSource(response.data.originator.name)
    })
    .catch((error) => {
      console.log(error)
    })
}

Remember to replace the API key value with your own API key.

Next, duplicate the TouchableHighlight component, but change the onPress attribute and the text in the Text component.

<TouchableHighlight onPress={axiosApiCall}>
  <View style={styles.button}>
    <Text style={styles.buttonText}>Use Axios</Text>
  </View>
</TouchableHighlight>

After saving the file, you can now use either button to call the API.

App.js should now have the code below.

import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View, TouchableHighlight } from 'react-native';
import axios from 'axios'

export default function App() {
  let [quote, setQuote] = React.useState('')
  let [source, setSource] = React.useState('')

  const fetchApiCall = () => {
    fetch("https://quotes15.p.rapidapi.com/quotes/random/?language_code=en", {
      "method": "GET",
      "headers": {
        "x-rapidapi-host": "quotes15.p.rapidapi.com",
        "x-rapidapi-key": "yourapikey"
      }
    })
      .then(response => response.json())
      .then(response => {
        setQuote(response.content);
        setSource(response.originator.name)
      })
      .catch(err => {
        console.log(err);
      });
  }

  const axiosApiCall = () => {
    axios({
      "method": "GET",
      "url": "https://quotes15.p.rapidapi.com/quotes/random/",
      "headers": {
        "content-type": "application/octet-stream",
        "x-rapidapi-host": "quotes15.p.rapidapi.com",
        "x-rapidapi-key": "yourapikey",
        "useQueryString": true
      }, "params": {
        "language_code": "en"
      }
    })
      .then((response) => {
        setQuote(response.data.content);
        setSource(response.data.originator.name)
      })
      .catch((error) => {
        console.log(error)
      })
  }

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Native API Calls</Text>
      <Text>Example with fetch and Axios</Text>
      <TouchableHighlight onPress={fetchApiCall}>
        <View style={styles.button}>
          <Text style={styles.buttonText}>Use Fetch API</Text>
        </View>
      </TouchableHighlight>
      <TouchableHighlight onPress={axiosApiCall}>
        <View style={styles.button}>
          <Text style={styles.buttonText}>Use Axios</Text>
        </View>
      </TouchableHighlight>
      <View>
        <Text>{quote}</Text>
        <Text>{source}</Text>
      </View>
      <StatusBar style="auto" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#AAA',
    alignItems: 'center',
    justifyContent: 'center',
    color: '#fff'
  },
  title: {
    fontSize: 35,
    color: '#fff'
  },
  button: {
    padding: 10,
    marginVertical: 15,
    backgroundColor: '#0645AD'
  },
  buttonText: {
    color: '#fff'
  }
});

5. Add Styling

Let’s add a little more style to the quote that is displayed.

Add the following properties to the styles object.

quote: {
  fontSize: 17,
  textAlign: 'center',
  fontStyle: 'italic'
},
source: {
  textAlign: 'right',
  marginTop: 15
},
quoteContainer: {
  marginHorizontal: 20,
  backgroundColor: '#fff',
  padding: 10,
  borderRadius: 5
}

Next, add the style attribute to each component. The quote View component will look like the below code.

....
      <View style={styles.quoteContainer}>
        <Text style={styles.quote}>{quote}</Text>
        <Text style={styles.source}>{source}</Text>
      </View>
....

The quote now has a little bit more style when it appears.

Conclusion

The tutorial took you through setting up a React Native application with Expo. This is not the only way to create React Native applications. However, this is the quickest and most compatible way to start developing.

Furthermore, the application did not go into all the things that Axios, fetch, and React Native can do. There is plenty more to explore with these libraries. This is a good application to start with and use to branch out with your new React Native skills. Follow the links below to learn more about the different libraries discussed in this article.

5 / 5 ( 1 vote )
Jarrett Retz

Jarrett is a Web and Automation Application Developer based in Spokane, WA. He is well versed in NodeJS, React, Django, Python, MongoDB, third-party APIs (i.e Sendgrid, Stripe), PostgreSQL, HTML5, CSS3, and cloud-computing resources. Learn more about Jarrett on his website.

Share
Published by

Recent Posts

API Testing Tutorial: API Testing with RapidAPI

What is API Testing? API testing is a type of software testing that involves testing application programming interfaces (APIs) directly…

6 days ago

Test APIs From Development to Deployment with RapidAPI Testing

We are excited to introduce RapidAPI Testing — a functional API testing solution for creating…

7 days ago

Build a Influencer Search App with Ruby on Rails

Internet search has gone way beyond the traditional web search. Thanks to other mediums of…

4 weeks ago

React API Authentication & Authorization

Introduction Security on the internet comes under scrutiny the more our personal lives and business…

4 weeks ago

How to use WordPress with React (WordPress React API Tutorial)

WordPress WordPress claims to be, "the world’s most popular website builder" based on the statistic…

1 month ago

How to use an E-mail API with JavaScript

Introduction This tutorial will show you how to use JavaScript to call an API to…

1 month ago