DEV Community

Carlos Junior
Carlos Junior

Posted on

1

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!

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay