
I needed to share how one can connect with your MetaMask account with React. The instance I’ll be demonstrating reveals how to connect with a MetaMask account, change accounts and alter your chain. All with a really small quantity of code.
This text assumes you have already got a MetaMask Account.
To get began you will want a brand new React venture, I used create-react-app
to get the whole lot up and operating rapidly.
After getting your software, go forward and set up these packages:
// npmnpm set up ethers @mui/materials @emotion/react @emotion/styled// yarnyarn add ethers @mui/materials @emotion/react @emotion/styled
Solely ethers are required, the others are simply to make issues look good
Create a new file in src for the element that can make the connection. I referred to as mine MetaConnect.js
.
Beneath is the complete code instance for making the connection. I’ll be going over every half individually beow.
State Variables
const [errorMessage, setErrorMessage] = useState(null);
const [account, setAccount] = useState(null);
const [balance, setBalance] = useState(null);
There are three items of knowledge to maintain observe of.
Occasion Listeners
useEffect(() =>
if (window.ethereum)
window.ethereum.on("accountsChanged", accountsChanged);
window.ethereum.on("chainChanged", chainChanged);
, []);
When the element first renders, arrange occasion listeners for accountsChanged
and chainChanged
. The arguments are features that might be defined additional down.
ConnectionHandler
const connectHandler = async () =>
if (window.ethereum)
attempt
const res = await window.ethereum.request(
technique: "eth_requestAccounts",
); await accountChange(res[0]);
catch (err)
console.error(err);
setErrorMessage("There was an issue connecting to MetaMask");
else
setErrorMessage("Set up MetaMask");
;
That is the perform that makes the preliminary connection MetaMask.
const res = await window.ethereum.request(
technique: "eth_requestAccounts",
);
This bit right here is the place the connection occurs, when MetaMask is put in, the window object has an ethereum
property to work together with. Once you name this perform, your MetaMask extension ought to open and ask what account you want to connect with.
Account Change
const accountsChanged = async (newAccount) =>
setAccount(newAccount); attempt
const steadiness = await window.ethereum.request(
technique: "eth_getBalance",
params: [newAccount.toString(), "latest"],
);
setBalance(ethers.utils.formatEther(steadiness));
catch (err)
console.error(err);
setErrorMessage("There was an issue connecting to MetaMask");
;
It is a helper perform that handles new accounts. It units the brand new account worth within the state, then will get and codecs the steadiness of the account.
The steadiness is requested utilizing an ethereum
JSON-RPC technique. You possibly can learn extra about it here
window.ethereum.request(
technique: "eth_getBalance",
params: [newAccount.toString(), "latest"],
);
As soon as the steadiness is obtained, it must be formatted
setBalance(ethers.utils.formatEther(steadiness));
The etheres
library has utility features to format a balance.
Altering Chains
const chainChanged = () =>
setErrorMessage(null);
setAccount(null);
setBalance(null);
;
It’s a good suggestion to do a connection reset whenever you change chains. For instance, transferring from Ethereum Mainnet to Ganache.
JSX
<Paper elevation=3 sx= p: 3 >
<Stack spacing=2>
<Typography variant="h6"> Account: account </Typography>
<Typography variant="h6">
Steadiness: steadiness steadiness ? "ETH" : null
</Typography>
<Button onClick=connectHandler>Join Account</Button>
errorMessage ? (
<Typography variant="body1" colour="crimson">
Error: errorMessage
</Typography>
) : null
</Stack>
</Paper>
Lastly, finish with some primary markdown to indicate values and supply a button to provoke the connection.
Conclusion
I hope this instance helps anybody seeking to get extra concerned with MetaMask of their React purposes.