DEV Community

Amit Ghosh
Amit Ghosh

Posted on • Edited on

Connect your React App with MetaMask wallet

While building any dApps on Ethereum blockchain, we face the task of connecting our web app to the MetaMask wallet.

What this essentially does is gives us access to the accounts associated with the MetaMask wallet. We need access to the accounts from MetaMask wallet to send any transaction from our dApp.

I am going to show you how to do this for a React web application.
First I'll show the code snippet and then explain it step by step.

const [walletConnected, setWalletConnected] = useState(false);

 const connectWallet = async () => {
 const accounts = await window.ethereum.request({ method: "eth_requestAccounts" });
  setWalletConnected(true);
  };  
Enter fullscreen mode Exit fullscreen mode

On the first line -

const [walletConnected, setWalletConnected] = useState(false);

We define a state variable to store the status of if wallet is connected. This can be used to display the "connect wallet" button conditionally.

Then we define a function connectWallet to be executed after clicking the "connect wallet" button. We need to pass this function to the onclick property like this.

<button onClick={connectWallet}>Connect Wallet</button>

This connectWallet function is an async function. Next this line of code

const accounts = await window.ethereum.request({ method: "eth_requestAccounts" });

requests MetaMask to be connected to the web app.

After executing this line of code, user will be prompted to connect on a new dialog box opened by MetaMask extension.

After the user has connected the account/accounts with the webapp, accounts is set to the list of accounts returned.

The next step is to access the connected accounts for the purpose of interacting with smarts contracts on the blockchain.

Usually we take the first account from the accounts array i.e. accounts[0] for the purpose of sending transactions. Because the first account is the currently selected account in MetaMask under my accounts settings.
eg:

await web3.eth.someMethod().send({from: accounts[0])

We also set walletConnected to true. Which can be used to conditionally render the connected status to the user, if needed.


There is another way to do this task of connecting to MetaMask .
First we import Web3 module from web3 library.

Web3 takes an argument of a provider to create an instance of Web3 object.

const web3 = new Web3(window.ethereum);

Here we pass the window.ethereum provider as an argument to Web3.

Now with this created instance web3 we can connect to MetaMask by using this line of code,

const accounts = await web3.eth.getAccounts();

And then again, as before we can use accounts[0] to access the currently selected account and use it to send transactions.

Top comments (0)