Introduction:
Have you ever wondered how to create a button that connects your website to a cryptocurrency wallet? In this tutorial, we will show you how to create a connect wallet button with React and MetaMask. By the end of this tutorial, you will be able to connect your website to your MetaMask wallet and display your account information on your website.
Prerequisites:
Before we get started, you should have some basic knowledge of React and MetaMask. If you're new to React, we recommend checking out the React documentation or taking a React tutorial. If you're new to MetaMask, we recommend installing MetaMask and creating a wallet.
Step 1: Set up the React app
First, let's create a new React app. Open your terminal and type the following command:
npx create-react-app my-app
Replace "my-app" with the name of your app. Once the app is created, navigate to the app directory by typing:
cd my-app
Step 2: Install MetaMask and Web3
To use MetaMask with your React app, you need to install the MetaMask extension and Web3 library. If you haven't already installed MetaMask, go to metamask.io and install the extension for your browser.
Next, in your terminal, type:
Recommended by LinkedIn
npm install web3
This will install the Web3 library, which we will use to interact with the MetaMask API.
Step 3: Create the ConnectWalletButton component
Now let's create the ConnectWalletButton component. In your src folder, create a new folder ConnectWalletButton and inside of it create a new file called "ConnectWalletButton.js". Copy and paste the following code into the file:
import React, { useState, useEffect } from 'react';import Web3 from 'web3';const web3 = new Web3(window.ethereum);const ConnectWalletButton = () => { const [account, setAccount] = useState(''); const [network, setNetwork] = useState(''); const [installed, setInstalled] = useState(false); const [isMobile, setIsMobile] = useState(false); useEffect(() => { if (window.ethereum) { setInstalled(true); const handleAccountsChanged = (accounts) => { setAccount(accounts[0]); } const handleChainChanged = (chainId) => { setNetwork(getNetworkName(chainId)); } window.ethereum.on('accountsChanged', handleAccountsChanged); window.ethereum.on('chainChanged', handleChainChanged); if (window.ethereum.selectedAddress) { setAccount(window.ethereum.selectedAddress); const networkId = window.ethereum.networkVersion; setNetwork(getNetworkName(networkId)); } else { setAccount(''); setNetwork(''); } } else { setInstalled(false); } if (window.innerWidth < 768 && navigator.userAgent.includes('Mobile')) { setIsMobile(true); } }, []); const handleConnectWallet = async () => { try { await window.ethereum.request({ method: 'eth_requestAccounts' }); const accounts = await web3.eth.getAccounts(); setAccount(accounts[0]); const networkId = await web3.eth.net.getId(); setNetwork(getNetworkName(networkId)); } catch (error) { console.error(error); } } const handleLogout = async () => { try { await window.ethereum.request({ method: 'wallet_requestPermissions', params: [{ eth_accounts: {} }] }); setAccount(''); setNetwork(''); } catch (error) { console.error(error); } } const getNetworkName = (networkId) => { switch (networkId) { case '1': return 'Mainnet'; case '3': return 'Ropsten'; case '4': return 'Rinkeby'; case '5': return 'Goerli'; case '42': return 'Kovan'; default: return ''; } } const openInMetamask = () => { const url = window.location.href; const mobileUrl = `metamask://open?url=${url}`; window.location.href = mobileUrl; } return ( <div> {installed ? ( account === '' ? ( <button onClick={isMobile ? openInMetamask : handleConnectWallet}>Connect Wallet</button> ) : ( <div> <p>{account}</p> <p>{network}</p> <button onClick={handleLogout}>Logout</button> </div> ) ) : ( <a href="https://metamask.io/download.html" target="_blank" rel="noreferrer"> Install Metamask </a> )} </div> );}export default ConnectWalletButton;
Step 4: Using the Connect Wallet Button
Now that we've created the ConnectWalletButton component, let's use it in our application. We'll add it to our main App component.
Here's the updated App.js file:
import React from 'react'import ConnectWalletButton from './components/ConnectWalletButton/ConnectWalletButton';function App() { return ( <div className="App"> <header className="App-header"> <h1>My DApp</h1> <ConnectWalletButton /> </header> </div> );}export default App;
We import the ConnectWalletButton component and add it to our App component.
That's it! We've created a ConnectWalletButton component that allows users to connect their wallet to our DApp. With this component, users can easily connect, disconnect, and switch between accounts and networks.
Final Thoughts
Web3 development can be complex, but it's important to remember that we're building for users. By creating intuitive and user-friendly components like the ConnectWalletButton, we can make Web3 development more accessible and user-friendly.
I hope you found this tutorial helpful. If you have any questions or feedback, please let me know in the comments!