Search⌘ K
AI Features

Solution: Creating a React Component

Explore how to create a React component that manages wallet connectivity in Web3 apps. Learn to use React hooks and Ethereum API methods to detect and display wallet connection status, enhancing your app's user interface and blockchain interaction capabilities.

Flowchart of a possible solution

In this challenge, you needed to create a React component called WalletMessage, which includes a button and a paragraph. On pressing the button, it’s expected that the connectivity of the wallet would be indicated with a message.

...
Python
import Web3 from "web3";
import {useEffect, useRef, useState,} from "react";
export default function Home() {
const web3 = useRef(null);
const [hasWalletWarning, setHasWalletWarning] = useState(false);
const [currentAccount, setCurrentAccount] = useState(null);
const connectWallet = async () => {
if (!checkIfWalletIsConnected()) {
return;
}
try {
const { ethereum } = window;
const accounts = await ethereum.request({
method: "eth_requestAccounts",
});
console.log("Connected", accounts[0]);
setCurrentAccount(accounts[0]);
} catch (error) {
console.log(error);
}
};
const checkIfWalletIsConnected = () => {
return Boolean(window.ethereum);
};
function MainButton({
onClick,disabled,label,
}) {
return (
<button onClick={onClick} disabled={disabled}>
<span>{label}</span>
</button>
);
}
useEffect(() => {
const hasWallet = checkIfWalletIsConnected();
setHasWalletWarning(!hasWallet);
}, []);
useEffect(() => {
if (web3.current) {
return;
}
if (!checkIfWalletIsConnected()) {
return;
}
web3.current = new Web3(window.ethereum);
web3.current.eth
.getBlock("latest")
.then((block) => console.log(block));
}, []);
return (
<div>
<main>
{!currentAccount && (
<div>
<MainButton onClick={connectWallet}
label={"Connect Wallet"}/>
</div>
)}
}
  • Line 3: We create the function Home(), which has the functions that are required to fulfill the task.

  • Lines 5–7: We pass the parameters to keep a check on the availability of the wallet by setting the useState hook to be false by default.

  • Lines 9–24: We create the check to see if the wallet is connected; if it is not, the connection will be made using etherum.request.

  • Lines 28–29: We create a boolean function that assures the availability of the wallet’s connection.

  • Lines 63–70: The main function prints Connect Wallet as the button.