How to add “connect button” to React Dapp?

By November 8, 2020DApps
Click here to view original web page at stackoverflow.com

On my UI i have a button tag

<button className="enableEthereumButton">Enable Ethereum</button>

And for my javascript im using the metamask code example

const ethereumButton = document.querySelector('.enableEthereumButton');

ethereumButton.addEventListener('click', () => {
  //Will Start the metamask extension
  ethereum.request({ method: 'eth_requestAccounts' });
});

How can i slap this onto my existing code? this here:

class App extends Component {

  async componentWillMount() {
    await this.loadWeb3()
    await this.loadBlockchainData()
  }

  async loadBlockchainData() {
    const web3 = window.web3
    const networkId = await web3.eth.net.getId()

    if(networkId!==4){
      window.alert('Please switch network to the Rinkeby and refresh the page')
    }

    const contract_abi = "abi goes here"
    const contract_address = '0x58d62c88981e798B97636d1D8C77e841f94E36CF' //rinkeby

    const contract = new web3.eth.Contract(contract_abi, contract_address);
    this.setState({ contract: contract })

    const accounts = await web3.eth.getAccounts()
    this.setState({ account: accounts[0] })

    const balance = await web3.eth.getBalance(this.state.account)
    this.setState({ balance: balance })

    const maxBet = await web3.eth.getBalance(contract_address)
    this.setState({ maxBet: maxBet })
  }

  async loadWeb3() {
    if (window.ethereum) {
      window.web3 = new Web3(window.ethereum)
      await window.ethereum.enable()
    }
    else if (window.web3) {
      window.web3 = new Web3(window.web3.currentProvider)
    }
    else {
      window.alert('Non-Ethereum browser detected. You should consider trying MetaMask!')
    }
  }

How can i implement above code snippet from metamask so my wallet connects once i hit the connect button?

<button className=”enableEthereumButton”>Enable Ethereum</button> And for my javascript im using the metamask code example

const ethereumButton = document.querySelector(‘.enableEthereumButton’); ethereumButton.addEventListener(‘click’, () => { […]

Leave a Reply