Connect button with MetaMask and React
I am working on a React app that connects to the Ethereum blockchain using MetaMask. I find it a bit intrusive when websites automatically connect the user’s account, so I wanted to use a button so the user could connect to the blockchain at their desire.
Here is how I went about it:
Firstly, I check to see if MetaMask is installed on the user’s browser and request the accounts and networkId from the window.ethereum
object:
const connectWallet = async () => { // Check if MetaMask is installed on user's browser
if(window.ethereum) { const accounts = await window.ethereum.request({ method: 'eth_accounts' }); const chainId = await window.ethereum.request({ method: 'eth_chainId'}); } else {
// Show alert if Ethereum provider is not detected
alert("Please install Mask");
}}
Next, I check to see if the user is connected to the correct network:
const connectWallet = async () => { // Check if MetaMask is installed on user's browser
if(window.ethereum) { const accounts = await window.ethereum.request({ method: 'eth_accounts' }); const chainId = await window.ethereum.request({ method: 'eth_chainId'}); // Check if user is connected to Mainnet
if(chainId != '0x1') {
alert("Please connect to Mainnet");
} else {
let wallet = accounts[0];
setWalletAddress(wallet);
} } else {
alert("Please install Mask");
}}
I am storing the user’s wallet address in a React state hook with setWalletAddress(wallet)
. For more information on React state, head over to the React.js docs: https://reactjs.org/docs/hooks-state.html
if(chainId != ‘0x1'){}
checks if the user is connected to the Ethereum Mainnet. Here is a list of Network and their corresponding chain ids from the MetaMask Ethereum Provider API:
Lastly, I return a button with the connectWallet
function as the onClick handler:
return (
<button className=”btn btn-light text-dark” onClick= {connectWallet}>Connect</button>
);
I am using Bootstrap 5 classes for the button styling, but feel free to use whatever styling framework you would like!
Thanks for reading! Hope this helps someone!