DEV Community

Carlos Junior
Carlos Junior

Posted on

How to make interaction with React.js and Smart-Contract

Hello fellow programmer, so on this tutorial i will teach how function in react works, lets get to work!

First of all you will need to use useEffect and useState

import React, { useEffect, useState } from "react";

and after

const [currentAccount, setCurrentAccount] = useState("");

this will creating a hook

On this code block
`const checkIfWalletIsConnected = async () => {
try {

const { ethereum } = window;

if (!ethereum) {
  console.log("Garanta que possua a Metamask instalada!");
  return;
} else {
  console.log("Temos o objeto ethereum", ethereum);
}
  /*
  * Confirma se estamos autorizados a acessar a carteira do cliente
  */
  const accounts = await ethereum.request({ method: "eth_accounts" });

  if (accounts.length !== 0) {
    const account = accounts[0];
    console.log("Encontrada a conta autorizada:", account);
    setCurrentAccount(account);
  } else {
    console.log("Nenhuma conta autorizada foi encontrada");
  }
Enter fullscreen mode Exit fullscreen mode

} catch (error) {
console.log(error);
}`

This will check the const ethereum that will be the blockchain we are currently using, and after that, and basically the method: gets the eth_accounts and checks with IF.

After that you will need to create the button is simples, all you need is

{!currentAccount && (
<button className="waveButton" onClick={connectWallet}>
Conectar carteira
</button>
)}

the function connectWallet will get the wallet and connect to it.

Good job you did it!

Top comments (0)