Web3.js – How to Connect React Web App to MetaMask Mobile Application

metamaskreactweb3js

I am looking for a way to connect metamask wallet to my react application using mobile (android and ios both), already integrated the wallet connection via chrome extension for desktop as follow

const initializeWeb3 = async () => {
    try {
      localStorage.setItem("meta-account", false);
      if (
        typeof window !== "undefined" &&
        typeof window.ethereum !== "undefined"
      ) {
        const accounts = await window.ethereum.request({
          method: "eth_requestAccounts",
        });
        web3js = new Web3(window.ethereum);
        setAccount(accounts[0]);
        setWeb3(web3js);
      }
      else {
        toast.error("Please install metamask!");
        ethereum.request({ method: 'eth_requestAccounts', params: [] });
      }

      window.ethereum.on("chainChanged", function (networkId) {
        window.location.reload();
      });
      window.ethereum.on("accountsChanged", (account) => {
        account = account;
        window.location.reload();
      });
      );
    } catch (error) {
      if (error.code == -32002) {
        toast.error("Metamask already opened!");
      }
      else {
        console.log(error);
      }
    }
  };

can anyone help me integrate the mobile connection as well

Best Answer

Turns out all I had to do was to include the metamask SDK in my reactJs application

import MetaMaskSDK from "@metamask/sdk";

and then create its instance, rest of the code remains the same

new MetaMaskSDK({
   useDeeplink: false,
   communicationLayerPreference: "socket",
});
Related Topic