How to connect MetaMask with React (For Beginner's)

How to connect MetaMask with React (For Beginner's)

Today we will learn how to connect MetaMask to React Dapp with the help of ether.js

Some Key Terminologies

  1. Singer

  2. Provider

  3. JsonRPC

1.Signer

Laymen Term
A Signer in Ethers. js is an object that represents an Ethereum account. It's used to send transactions to contracts and other accounts.

Technical Term

A Signer is a class which is (usually) in some way directly or indirectly has access to a private key, which can sign messages and transactions to authorize the network to charge your account ether to perform operations.

note: we will be using Signer in our other tutorials for now just understand it.

2.Provider

A Provider is an abstraction to the Ethereum Network that allows developers to connect to a standard Ethereum node permitting read-only access to the blockchain.

3.jsonRPC

The JSON-RPC API is a popular method for interacting with Ethereum and is available in all major Ethereum node implementations (e.g. Geth and Parity) as well as many third-party web services (e.g. INFURA)

To Learn More about [ jsonRPC ]

Requirement

  1. React.js

  2. Ether.js

  3. MetaMask

Steps

1.Create React app

open the terminal and paste the following command to install react modules

// npx create-react-app "_name_of_App_"

npx create-react-app connectmetamask

2.Installing Ethers.js

again enter the following command in terminal

npm i --save ethers

3.Code to connect MetaMask

import {ethers} from 'ethers'
....
..

// proivder 
// web3Provider is a standard method to web3 provider

const provider = new ethers.BrowserProvider(window.ethereum)

const accounts = await provider.send(reqAccounts,[]);

console.log(accounts[0])

what is window.ethereum?

MetaMask injects a global JavaScript API into websites visited by its users using the window. Ethereum provider object. This API allows websites to request users' Ethereum accounts, read data from blockchains the user is connected to, and suggest that the user sign messages and transactions.

// state for storing walletAddress
const [wallet,setWallet] = useState("")

// onClick handler
const openMetaMask = async() => {
    // string will be passed in as a argument for fetching accounts from     wallet
    let reqAccounts = "eth_requestAccounts"

    const provider = new ethers.BrowserProvider(window.ethereum)
    const accounts = await provider.send(reqAccounts,[]);
    // provider.send() will returns an array of string which represent                             walletAddress

    console.log(accounts[0])
    setWallet(accounts[0])
};

check out the full-source code on github go Check-it-out

https://github.com/Nishchit-Dev/HashNode/tree/master/connectmetamask

For Amazing Content Follow me on Twitter

Kids Goku Peace GIF - Kids Goku Peace Cool - Discover & Share GIFs

Did you find this article valuable?

Support Nishchit Malasana by becoming a sponsor. Any amount is appreciated!