Initialize Web3 on Client Side

web3.js allows developers to interact with the blockchain without running the Node

Web3 is a JavaScript Library to interact with Ethereum Blockchain.

The following code shows a new way to start up a dapp that can be used today in both legacy and modern dapp browsers:

Install web3

npm install web3
import React, { useState, useEffect } from "react";
import Web3 from 'web3'

let web3;

function App() {
  
  useEffect(() => {
    (async () => {
      if (window.ethereum) {
        // Modern DApp browsers
        web3 = new Web3(window.ethereum);
        try {
          await window.ethereum.enable();
        } catch (error) {
          // User denied account access
          console.log(error);
        }
      } else if (window.web3) {
        // Legacy dapp browsers
        web3 = new Web3(window.web3.currentProvider);
      } else {
        // Non-dapp browsers
        console.log("Non-Ethereum browser detected. You should consider trying MetaMask!");
      }
    })(); 
  }, []);


  return (
    <div className="App">
      {/* HTML code here*/}
    </div >
  );
}

export default App;

Here's an article from Metamask for further understanding of initialising web3

Last updated