I'm trying to create my first dapp using React. I can't understand how connecting Web3.js to React and how to use it right. Can you show how to do it correctly?
Maybe I should use state.
import React, { Component } from 'react';
import Web3 from 'web3';
import ABI from './web3/ABI'
class App extends Component {
web3Connection = () => {
let web3
if (window.ethereum) {
web3 = new Web3(window.ethereum);
try {
window.ethereum.enable().then(function() {});
} catch (e) {}
} else if (window.web3) {
web3 = new Web3(web3.currentProvider);
} else {
alert('You have to install MetaMask !');
}
web3.eth.defaultAccount = web3.eth.accounts[0];
const EthereumNoteContract = web3.eth.contract(ABI);
const EthereumNote = EthereumNoteContract.at('address');
}
addMyNote = (_text) => {
EthereumNote.addMyNote(_text, { value: 0 }, function(error, result) {
if (error) console.log(error);
else console.log(result)
});
}
render() {
return (
<div>
{this.web3Connection}
<button onClick={this.addMyNote}>Send</button>
</div>
)
}
}
Assuming that you have the metamask chrome extension installed and are loggedin... Also assuming that you have installed the web3 lib...
Here you go:
import React from 'react';
import Web3 from 'web3'
export default class App extends React.Component {
state = {account: ''}
async loadBlockChain() {
const web3 = new Web3(Web3.givenProvider || 'http://localhost:8080')
const network = await web3.eth.net.getNetworkType();
console.log(network) // should give you main if you're connected to the main network via metamask...
const accounts = await web3.eth.getAccounts()
this.setState({account: accounts[0]})
}
componentDidMount() {
this.loadBlockChain()
}
render() {
return (
<div>
<p>Check out the the console....</p>
<p>Your account: {this.state.account}</p>
</div>
);
}
}
Functional / Hooks:
import React, { useState, useEffect } from "react";
import Web3 from "web3";
export default function App() {
const [account, setAccount] = useState("");
async function loadBlockChain() {
const web3 = new Web3(Web3.givenProvider || "http://localhost:8080");
const network = await web3.eth.net.getNetworkType();
console.log(network); // should give you main if you're connected to the main network via metamask...
const accounts = await web3.eth.getAccounts();
setAccount(accounts[0]);
}
useEffect(() => loadBlockChain, []);
return (
<div>
<p>Check out the the console....</p>
<p>Your account: {account}</p>
</div>
);
}