Connecting React application with Metamask wallet

Nimasha Bandara
5 min readMar 23, 2022

--

In this article I am going to share my experience on connecting a React application with Metamask wallets. Digital wallets are supported to allow decentralization. Hence using these wallets, users can connect to software applications much easily without creating user accounts for each and every application.

What is metamask ?

Metamask is a famous crypto wallet which is available as a browser extension and mobile application. It supports most common browsers such as Google Chrome, Firefox and Microsoft Edge etc. metamask enables easy interaction with applications connected to blockchain. When you create a metamask wallet you will get a private key which is stored in your wallet and metamask servers store nothing about your private key. With metamask, we can create more than one wallet with us with different key pairs.

Scenario

Here I am going to create a very simple single page react application. My objective is to connect my react application to metamask wallet and let users to sign in via metamask wallet account. After the user logged in the account balance and public wallet address of the user will be displayed.

Step 1: First we need to install the metamask browser extension.

Go to https://metamask.io/download/ and install metamask for chrome.

Then you need to create a wallet account.

Create wallet → create password → get the recovery phase(master key)

Now you have the metamask browser extension in chrome. You will see orange color fox icon in extension corner.

You can avoid this step if you want to let your application direct you to metamask installation. In my application, I direct users to the installation page who did not install metamask beforehand.

Step 2: let’s build our simple react application.

You can start the process by creating a react application.

Run: ‘npx create-react-app <Name of app>’ command by giving a suitable name for the application.

Step 3: we need to install the ethers package and @metamask/onboarding.

Run:

npm install -save ethersnpm install @metamask/onboarding

You can check in the package.json file to ensure these packages are installed.

Step 4: Let’s create the logic of our single page application in the App.js file. This is the component which is rendered to the browser.

Step 4.1: Let’s import necessary packages first.

We need to import the above packages to our App.js file.

import { ethers } from "ethers";import MetaMaskOnboarding from "@metamask/onboarding";

I have imported the useState hook for handing the state of the application.

import { useState } from "react";

Note : Latest versions of react does not require importing the react package to files.

Step 4.2: we can create the necessary state variables of our application. In this case I have created three constants as logged, account and balance. The logged variable stores the log in status of the user. Logged variable is a boolean type where it marks True when the user is logged to the application via metamask account. Account variable is for holding the account address while the balance variable will be used to store the balance of a particular account.

const [logged, setLogged] = useState(false);const [account, setAccount] = useState(null);const [balance, setBalance] = useState();

This is how constants at the initial state.

Step 4.3: Create constants for directing the user to install metamask browser extension if necessary.

const forwarderOrigin = "http://localhost:3000";

your url where the application is running. After installing you will be directed to here again.

const onboarding = new MetaMaskOnboarding({ forwarderOrigin });

creating MetamaskOnboarding object from Onboarding library which we have imported above from @metamask/onboardingpackage.

Step 4.4: Now let’s create the most important function of our application which is handling the log in process via metamask account.

const { utils } = require("ethers");

first have utils from ethres to convert your account address which is returned as only simple letters by eth_requestAccounts method.

In the function we first check whether the metamask is installed to the current browser. If metamask is installed it requests for the metamask accounts using ‘eth_requestAccounts’ method where you will see a metamask pop up window asking to choose your metamsk account. After you click next, you will be asked to connect. That’s it. Now you are logged in. The above request makes a promise to return a string array of account address of your wallet. I have logged state True by ‘setLogged(True)’ and account variable to current wallet address by ‘setAccount(result[0])’.

If metamsk is not installed, the user will be directed to installation by the ‘onboarding.startOnboarding()’ statement.

Step 4.5: Let’s create a function for getting the balance of your wallet.

This is done via the “eth_getBalance” method request and there are two parameters as account and ‘latest’ which means the latest account. Then I have set the balance state in setBalance(ethers.utils.formatEther(balance)). Here we have used the ethers package to convert the hexadecimal value we are given from metamask into floating points.

Step 4.6: Now lets create the log out function. Even though we have this function, metamask needs us to log out manually from the metamask account. This is just to go back to log in view.

const hnadleLogout = () => {setLogged(false);setAccount(null);};

Step 5: As a final step, let’s make a view of our simple react application in the App.js file. In my case, it is only a few headers and buttons.

I have checked the logged state and rendered different views according to the logged state. The three buttons Log In, Log Out and Check balance called relevant functions at the onClick event. That is it.

This is the full code :

Your final result looks like this.

Click log in

Click next after choosing account

Click connect

Check balance

--

--