Boilerplate to connect React app to Web3 using Metamask.
Wrap your App in <MetamaskProvider></MetamaskProvider>
App.jsx
import { MetamaskProvider } from ". /metamask";
import HelloMetamask from "./components/HelloMetamask";
export default function App() {
return (
<MetamaskProvider>
<HelloMetamask />
</MetamaskProvider>
);
}
Use the component <ConnectMetamask />
to request access to use Metamask
import React from "react";
import { useMetamask, ConnectMetamask } from "../metamask";
export default function MyWallet(props: any) {
const { user } = useMetamask();
if (!user.isConnected) return <ConnectMetamask />
return <div>My wallet is: {user.address}</div>;
}
loadSmartContract(address, abi)
to get a handler for your Smart Contractcontract
is the object with methods and variables from your Smart Contract
import { useMetamask, ConnectMetamask, loadSmartContract } from "../metamask";
import dapp from "../metamask/dapp";
export default function HelloMetamask() {
const { user, contract, setContract } = useMetamask();
const setSmartContract = () => {
const smartContract = loadSmartContract(dapp.address, dapp.abi);
setContract(smartContract);
};
useEffect(() => {
setSmartContract();
}, []);
return <div>My first dapp!</div>
}
You are ready! 🚀🚀