Using Ethers v6 library connect Metamask to React Application
Metamask is a well-known browser extension that allows users to interact with the Ethereum blockchain effortlessly. In this step-by-step guide, we’ll explore how to connect Metamask to React website using the ethers.js library
By the end of this tutorial, you’ll be able to
✅ verify whether Metamask is installed
✅ connect to users’ wallets and fetch the user details
Step 1: Install the Ethers Library
The Ethers.js library must be installed in the React project. Either yarn or npm can be used:
#Using npm npm install ethers #Using yarn yarn add ethers |
Step 2: Checking Metamask Installation
The first step the metamask extension is installed or not in the chrome brower or any other brower In case it’s not installed, we’ll prompt the user to install Metamask for a smooth experience.
const checkMetamaskInstallation = () => { if (window.ethereum == undefined) { alert(“Metamask wallet is not installed”); return; } }; |
The window.ethereum object is available, which is injected by MetaMask.
Step 3 : Initiating Wallet Connection and fetch the user details
Once the Metamask is installed, the next step is to establish a connection between the user’s wallet and our metamask . With the connection established, we’ll have the user’s account address available for further interactions.
const [account, setAccount] = useState<string | null>(null); const [balance, setBalance] = useState<string | null>(null); const connectToMetaMask = async () => { setIsLoading(true); try { if (window.ethereum?.isMetaMask) { const provider = new ethers.BrowserProvider(window.ethereum); const accounts = await provider.send(“eth_requestAccounts”, []); const account = accounts[0]; setAccount(account); const balance = await provider.getBalance(account); const ethBalance = ethers.formatEther(balance); setBalance(ethBalance); setErrorMessage(“”); } else { setErrorMessage(“Please install MetaMask extension!”); setSnackbarOpen(true); } } catch (error: any) { setErrorMessage(`Error connecting to MetaMask: ${error.message}`); setSnackbarOpen(true); } finally { setIsLoading(false); } }; |
How it operates:
- We check window.ethereum?.isMetaMask to confirm MetaMask’s availability.
- ethers.BrowserProvider(window.ethereum) is used to create a provider.
- eth_requestAccounts is used to request account access.
- Ethers are used to retrieve the ETH balance and account address.
- ethers.formatEther() is used to convert the balance from Wei to ETH.
UI Implementation Example
To connect MetaMask, we can add a straightforward button to the React component:
<button onClick={connectToMetaMask}>Connect Wallet</button> {account && <p>Account Connected: {account}</p>} {balance && <p>Balance: {balance} ETH</p>} |