How to connect ReactJS with MetaMask ?
Blockchain is the backbone of cryptocurrency and web 3.0. The world is accepting blockchain technology and also accepting decentralization applications due to transparency in different transactions. NFT is trending and mostly NFT DAPP runs on the Ethereum blockchain. In this article, we will take a look, at how one can connect theirs react js application to Meta mask wallet which is the most used browser tool for sending and receiving signed transactions.
MetaMaks: MetaMask is a crypto wallet and a gateway to blockchain DAPP. It is used to connect our app to web3. It is just a chrome extension that is used to access and interact with the Ethereum blockchain. Its features support tokens and digital assets on the Ethereum ecosystem. It is also used as a primary wallet to store the balance in Ethereum.
For connection, we are using ethers.js, in order to connect to the Ethereum wallet.
Creating React Application:
Step 1: Creating a react project with CLI
npx create-react-app eth_app or yarn create react-app eth_app
Project structure: It will look like the following.
Step 2: Connecting Metamask to react app. For achieving the meta mask wallet address we need to connect MetaMaks to our react app. For checking, if meta mask is connected.
if(window.ethereum){ // Do something }else{ alert("install metamask extension!!") }
Now, if meta mask is installed we need to request the account.
window.ethereum.request({method:'eth_requestAccounts'}) .then(res=>{ // Return the address of the wallet console.log(res) })
For getting the balance we need to request the balance method
window.ethereum.request({ method:'eth_getBalance', params: [address, 'latest'] }).then(balance => { // Return string value to convert it into int balance console.log(balance) // Yarn add ethers for using ethers utils or // npm install ethers console.log(ethers.utils.formatEther(balance)) // Format the string into main latest balance })
Step 3: Pull the information in to react. For fetching the information into react page, we will use useState for setting the value from the javascript method and using into jsx
const [data, setdata] = useState({ address:'', // Stores address Balance: null // Stores balance })
App.js
// Importing modules import React, { useState } from "react" ; import { ethers } from "ethers" ; import "./App.css" ; import { Button, Card } from "react-bootstrap" ; import "bootstrap/dist/css/bootstrap.min.css" ; function App() { // usetstate for storing and retrieving wallet details const [data, setdata] = useState({ address: "" , Balance: null , }); // Button handler button for handling a // request event for metamask const btnhandler = () => { // Asking if metamask is already present or not if (window.ethereum) { // res[0] for fetching a first wallet window.ethereum .request({ method: "eth_requestAccounts" }) .then((res) => accountChangeHandler(res[0])); } else { alert( "install metamask extension!!" ); } }; // getbalance function for getting a balance in // a right format with help of ethers const getbalance = (address) => { // Requesting balance method window.ethereum .request({ method: "eth_getBalance" , params: [address, "latest" ] }) .then((balance) => { // Setting balance setdata({ Balance: ethers.utils.formatEther(balance), }); }); }; // Function for getting handling all events const accountChangeHandler = (account) => { // Setting an address data setdata({ address: account, }); // Setting a balance getbalance(account); }; return ( <div className= "App" > { /* Calling all values which we have stored in usestate */ } <Card className= "text-center" > <Card.Header> <strong>Address: </strong> {data.address} </Card.Header> <Card.Body> <Card.Text> <strong>Balance: </strong> {data.Balance} </Card.Text> <Button onClick={btnhandler} variant= "primary" > Connect to wallet </Button> </Card.Body> </Card> </div> ); } export default App; |
Output: