Search
Generic filters
Share on facebook
Share on twitter
Share on linkedin

Create Mobile Ethereum dApp with React Native Template

When it comes to creating decentralized applications (dApps), Ethereum remains the most popular option among developers. However, many developers do not have a mobile-first approach when developing dApps, which is quite an issue since most users spend more time on their mobile devices. Moreover, if Web3 applications do support mobile users, they usually offer a poor user experience starting with login complications and faulty wallet integration. This leads to both experienced and new crypto users leaving your dApp for the competition. Fortunately, there is a practical solution that enables you to create user-friendly mobile dApps easily. Furthermore, this excellent solution also gives you a chance to deploy any mobile Ethereum dApp on other leading chains. This is possible when using tools such as Moralis and a React Native template. As such, we’ll show how to create a mobile Ethereum dApp with a React Native template herein.

Unless you’ve been living under a rock, you’ve probably heard of Moralis before. This ultimate Web3 development platform enables frontend developers to easily transition to blockchain development and deliver phenomenal dApps markedly quicker. This is possible thanks to Moralis’ services, including Moralis Speedy Nodes, servers, a powerful Web3 SDK, and an extensive API. Through the power of these tools, Moralis makes blockchain development as simple as it can be. Moreover, with its latest addition, React Native support, it also covers mobile Ethereum dApp development. By using a React Native template, you can create user-friendly mobile dApps with minimal effort. Moreover, Moralis was built with cross-chain interoperability in mind from its inception. As such, your mobile Ethereum dApp, built with Moralis, can be deployed on other reputable chains. That way, you also future-proof your dApps and eliminate a lot of risk in case any chain loses popularity. 

What is a React Native Template?

Before we give you a chance to take a closer look at an example project, where we create a simple mobile Ethereum dApp using the tools mentioned above, we must first get you all up to speed. Thus, we need to cover some basics in order to ensure that you get a proper understanding of mobile dApps development. So, what is a React Native template? 

First, you need to know that React Native is similar to React; however, it utilizes native components instead of web components as building blocks. It enables you to develop mobile applications that work on different platforms. If you are not familiar with React and want to dive deeper into the topic, we recommend checking out our article called “What is React?”. However, we can describe React briefly for basically being an open-source, declarative JavaScript (JS) user interface (UI) library. It uses a templating language called “JSX”, which compiles code to plain JavaScript functions. As such, by knowing React, you know the basics for using any React Native template. Moreover, one should also learn some React Native-specific aspects, especially the native components.

As such, a React Native template is any pre-written React Native code for a mobile application, with documentation and a set of mobile app design-based features. Like any template, it is an excellent starting point; however, it requires some tweaking to meet your required needs. Check out our React dApp template for a step-by-step guide!

In case you are a complete beginner wanting to become a blockchain developer, you first need to ensure that you know at least one of the best languages for blockchain development. JavaScript in combination with React is quite powerful; thus, we recommend enrolling in Moralis Academy’s JavaScript Programming for Blockchain Developers and React Web Development 101 courses.

React-Moralis – Mobile dApps Development Made Easy

What is React-Moralis? React-Moralis refers to Moralis’ support for React and React Native, which enables mobile Ethereum dApp developers to easily call functionalities and display data using Moralis’ powerful platform. Essentially, React-Moralis enables you to use the power of Moralis and Web3 on any mobile platform. With the use of this integration, you can easily overcome the limitations that most dApps face. As such, you get to meet the needs of web and mobile users. That way, you get to deliver a great user experience with ease for mobile device users who are interested in decentralized applications.

Create a User-Friendly Mobile Ethereum dApp – React-Moralis Quick Start

First, you need to make sure that “react”, “react-dom”, and “moralis” dependencies are installed inside your code editor (we typically use Visual Studio Code [VSC]). Next, you install the “react-moralis” dependency. All of this is covered by entering the following in VSC’s terminal:

  • If you use npm package manager:  npm install react react-dom moralis react-moralis
  • If you use yarn package manager:  yarn add react react-dom moralis react-moralis

Then, you need to wrap your app in a “<MoralisProvider>”. Moreover, you should provide your “appId” and “serverUrl” (for more info, see the next subsection):

import React from "react";
import ReactDOM from "react-dom";
import { MoralisProvider } from "react-moralis";

ReactDOM.render(
  <MoralisProvider appId="xxxxxxxx" serverUrl="xxxxxxxx">
    <App />
  </MoralisProvider>,
  document.getElementById("root"),
);

All that is left to do now is call the hooks inside your app:

import React from "react";
import { useMoralis } from "react-moralis";

function App() {
  const { authenticate, isAuthenticated, user } = useMoralis();

  if (!isAuthenticated) {
    return (
      <div>
        <button onClick={() => authenticate()}>Authenticate</button>
      </div>
    );
  }

  return (
    <div>
      <h1>Welcome {user.get("username")}</h1>
    </div>
  );
}

Moralis Setup – Getting Application ID and Server URL

To obtain a Moralis server’s application ID and server URL, follow these steps:

  1. Create Your Moralis Account – In case you haven’t created your Moralis account yet, make sure to do so now. Just click the link above, enter your email address, and create your password. Then, confirm your email address (you’ll receive an email with a confirmation link). If you already have a Moralis account, just log in
  2. Create a New Server – After logging in to your Moralis account, you want to create a new server. Just click the “+ Create a new Server” button in the top-right corner and select the preferred network type from the drop-down menu (see the image below). The “Testnet Server” option is an excellent choice when developing a new project.


Next, enter the required details, including server name (it can be anything you want), select region, network, chain(s) (you can select one or multiple options), and click “Add Instance”.

  1. Access Server Details – To obtain your server’s URL and application ID, just click the “View Details” button next to your server name. A pop-up window will appear containing all of the information (see the image below). If you’ve used Moralis before, you may already have one or more servers set up. In that case, you can use any of them.
  1. Initialize Moralis – Now, you need to populate your code with the Moralis server details (application ID and server URL). That way, you obtain the required backend functionality:

Note: Do not copy the server details from the image above. You need to use the details of your particular server.

Create Mobile Ethereum dApp with React Native Template – an Example Project

Now, it’s finally time to use a React Native template and create a mobile Ethereum dApp as an example project. That way, you’ll see how Moralis simplifies things. For instance, Moralis also makes the implementation of Ethereum authentication to your dApp straightforward. For our demo dApp, we will be using WalletConnect. Here’s how our demo app looks like:

In the steps shown above, we first initiate our demo mobile dApp. Next, we tap the “Authenticate with crypto wallet” button. This activates the WalletConnect authentication option, which offers various alternatives. For the purpose of this example, we use MetaMask’s wallet app. Then we need to click the “Connect” button and then the “Sign” button within the MetaMask wallet app that is automatically launched. Finally, we can see that our mobile Ethereum dApp is logged in and shows several details. The latter include user name (stored in Moralis’ database), user email (if provided), user address, and native balance.

This is a basic example of a mobile Ethereum dApp, but it shows you that it fetches the on-chain data, which is the main purpose. Let’s now take a closer look at the code that is required to create such mobile dApps.

React Native Template for Mobile dApps – Code Walkthrough

To create the mobile-friendly Ethereum dApp presented above, we use multiple TypeScript (.tsx) files, which contain all the needed code. Furthermore, we made all these files available to you at GitHub (React Native boilerplate). Feel free to use them as React Native templates for your mobile dApps.

Looking at the “Providers.tsx” file (click the link above to view the complete code), there are certain parts of the code that deserve some extra attention. For one, we need to initialize Moralis (this is where we use the details obtained in the “Moralis Setup – Getting Application ID and Server URL” subsection):

const appId = "INSERT_APP_ID"; // Application ID from moralis.io
const serverUrl = "INSERT_SERVER_URL"; // Server URL from moralis.io
const environment = "native";
const getMoralis = () => Moralis;
// Initialize Moralis with AsyncStorage to support react-native storage
Moralis.setAsyncStorage(AsyncStorage);
// Replace the enable function to use the react-native WalletConnect
// @ts-ignore
Moralis.setEnableWeb3(enableViaWalletConnect);

This provides you with full access to Moralis’ API, including its advanced NFT API, Ethereum API, and many other powerful shortcuts. Now, let’s take a look at another important part of the code ensuring that we initialize Moralis and WalletConnect:

export const Providers = ({ children }: ProvidersProps) => {
  return (
    <WalletConnectProvider {...walletConnectOptions}>
      <MoralisProvider appId={appId} serverUrl={serverUrl} environment={environment} getMoralis={getMoralis}>
        {children}
      </MoralisProvider>
    </WalletConnectProvider>
  );
};

React Native Template for Mobile dApps – The “App.tsx” File

The “App.tsx” file contains the code that provides our example app with all the functionalities and UI components. The entire code is too extensive for us to fully cover herein (to view the complete code, click the link above); however, let’s take a look at the lines of code for the “hook calls”:

import React, { useEffect } from "react";
import { StyleSheet, Text, TouchableOpacity, View } from "react-native";
import { useMoralis, useMoralisWeb3Api, useMoralisWeb3ApiCall } from "react-moralis";
import { useWalletConnect } from "./WalletConnect";

Furthermore, this is the file containing the code that ensures user details are obtained and displayed properly and that WalletConnect is used to authenticate users:

  • The function that covers token balances (just a part of the code is displayed):
    Moralis.Web3API.account.getTokenBalances({ address: "" }).then(console.log);
  }, []);
  • The function that takes care of authentication and displaying users’ details:
function App(): JSX.Element {
  const connector = useWalletConnect();
  const { authenticate, authError, isAuthenticating, isAuthenticated, logout, Moralis } = useMoralis();

  return (
    <View style={[StyleSheet.absoluteFill, styles.center, styles.white]}>
      <View style={styles.marginLarge}>
        {authError && (
          <>
            <Text>Authentication error:</Text>
            <Text style={styles.margin}>{authError.message}</Text>
          </>
        )}
        {isAuthenticating && <Text style={styles.margin}>Authenticating...</Text>}
        {!isAuthenticated && (
          // @ts-ignore
          <TouchableOpacity onPress={() => authenticate({ connector })}>
            <Text>Authenticate</Text>
          </TouchableOpacity>
        )}
        {isAuthenticated && (
          <TouchableOpacity onPress={() => logout()}>
            <Text>Logout</Text>
          </TouchableOpacity>
        )}
      </View>
      {isAuthenticated && (
        <View>
          <UserExample />
          <Web3ApiExample />
        </View>
      )}
    </View>
  );
}

If you prefer to watch video explanations, we recommend watching the following video: 

Mobile dApps – Email Authentication

Those of us who are deeply involved with blockchain and crypto applications tend to forget that the average person has no idea what crypto wallets are. For those users, you may want to offer an option to use email authentication in your dApp. With that, you get to blur the lines between Web2 and Web3, offering the best user experience to a wider population. Moreover, you get to onboard new crypto users by offering the email login option that they know and then guiding them through the process of connecting their wallets. This will serve as an excellent way to onboard them to the crypto realm and make them appreciate your mobile Ethereum dApp right away. 

In case you are interested in learning more about basic user registration and login options, make sure to click the link.

Create Mobile Ethereum dApp with React Native Template – Summary

Moralis just made creating mobile dApps a whole lot easier. By using Moralis’ ultimate Web3 development platform that supports React Native, you get to take advantage and benefit from the most advanced Web3 API. By using short snippets of code, you get to cover otherwise tedious and time-consuming blockchain-related backend coding. Those snippets of code are neatly provided in Moralis’ documentation, accompanied with examples to help you grasp things quickly. With Moralis’ React Native support, you get to front-run other projects limited to web users or those who do not know how to offer their mobile users a simple way to access the Web3 world. 

Furthermore, please keep in mind that with Moralis, you are by no means limited to mobile dApps on the Ethereum chain. Moralis was created to be completely cross-chain interoperable and is constantly adding support for new reputable chains. While Ethereum is considered as the native option, you can focus on any other supported chain by simply adding an additional parameter that specifies another chain. Moreover, this cross-chain interoperability makes Moralis the best Infura for Avalanche and Infura for BSC alternative. As such, it also enables you to overcome all the limitations of RPC nodes.

In addition, we recommend exploring the free content we continue to provide on Moralis’ blog and Moralis’ YouTube channel. Aside from explaining various aspects of blockchain development, we cover many example projects that may serve as great learning and inspirational material. 

October 27, 2021
Moralis Blog
Moralis Blog
Become a Moralis Mage
Get the latest information about Moralis Web3 in your email
Search
Generic filters
Related Articles
Become a Web3 Expert
Subscribe to our newsletter and get our E-book Web3 Speed run for FREE