TechAE Blogs - Explore now for new leading-edge technologies

TechAE Blogs - a global platform designed to promote the latest technologies like artificial intelligence, big data analytics, and blockchain.

Full width home advertisement

Post Page Advertisement [Top]

Add Web3Modal in React

Introduction

Today, we'll look at how to use the well-known Web3Modal to provide multi-wallet functionality on our react js website. This tutorial will be built on a react example website that uses basic bootstrap components and then accesses the modal with a single button, giving multiple wallets at the same time.

Step 1: Creating React App

The easiest way to create react app with all recommended dependencies, you’ll need to have Node >= 14.0.0 and npm >= 5.6 on your machine. To create a project, run:

npx create-react-app my-app
cd my-app
npm start

Step 2: Creating Button using Bootstrap

Let's import the Bootstrap 5 using CDN in our index.html. You can get the free open-source CDN links from the official bootstrap page but I am still pasting the links here for easier access

CSS

Copy and paste this link in between <head> and </head> tags of your index.html document

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

JS

Copy and paste this link right before the closing </body> tag.

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

As soon as you put the above links in index.html in the right place, Bootstrap 5 will be enabled instantly. Now, let's create a button component in our App.js file.

You can get some different button components from the Bootstrap website, I am gonna use btn-primary for this project.

import logo from "./logo.svg";
import "./App.css";

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>How To Add Web3Modal in React Example</p>
        <button className="btn btn-primary">Connect Wallet</button>
      </header>
    </div>
  );
}

export default App;

Now, when you open http://localhost:3000/, you will see your live UI.

React UI

Step 3: Adding Web3Modal packages

To add Web3Modal, we have to install the Web3Modal NPM package. Open your terminal and write the code below:
npm install --save web3modal
# OR
yarn add web3modal

Then you have to install provider packages, I will list down the available provider options:

  1. Metamask (default)
  2. WalletConnect
  3. Binance Chain Wallet
  4. Coinbase Wallet
  5. Fortmatic
  6. Torus
  7. Portis
  8. Authereum
  9. Frame
  10. Bitski
  11. Venly
  12. DCent
  13. BurnerConnect
  14. MEWConnect
  15. Sequence
For this project, I will use Wallet Connect, Binance Chain Wallet, and Coinbase Wallet. When you click the above packages link, you will be taken to the instructions to install these relevant packages.
npm install --save @coinbase/wallet-sdk
npm install --save @walletconnect/web3-provider
# OR
yarn add @coinbase/wallet-sdk
yarn add @walletconnect/web3-provider
For easier access, you can install the above Wallet Connect and Coinbase Wallet packages, whereas Metamask is available by default, and Binance Chain Wallet doesn't require any installation.

Step 4: Add Web3Modal to your Dapp

Now, we shall write the separate functions for connecting wallet and web3modal, add this code in your App.js file before your functional/class component.
import Web3 from "web3";
import Web3Modal from "web3modal";
import WalletConnectProvider from "@walletconnect/web3-provider";
import CoinbaseWalletSDK from "@coinbase/wallet-sdk";

const providerOptions = {
  walletconnect: {
    package: WalletConnectProvider, // required
    options: {
      infuraId: "INFURA_ID", // required
    },
  },
  coinbasewallet: {
    package: CoinbaseWalletSDK, // Required
    options: {
      appName: "web3modal", // Required
      infuraId: "INFURA_ID", // Required
      rpc: "", // Optional if `infuraId` is provided; otherwise it's required
      chainId: 1, // Optional. It defaults to 1 if not provided
      darkMode: false, // Optional. Use dark theme, defaults to false
    },
  },
  binancechainwallet: {
    package: true,
  },
};

const web3Modal = new Web3Modal({
  network: "mainnet", // optional
  cacheProvider: true, // optional
  providerOptions, // required
});

const connectWallet = async () => {
  if (window.ethereum) {
    const provider = await web3Modal.connect();
    const web3 = new Web3(provider);
    await window.ethereum.send("eth_requestAccounts");
    const accounts = await web3.eth.getAccounts();
    const account = accounts[0];
    document.querySelector(".connect").innerHTML = account;
  } else {
    // Show alert if Ethereum provider is not detected
    alert("Please install Mask");
  }
};

Update the functional component also:

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>How To Add Web3Modal in React Example</p>
        <button type="button" className="btn btn-primary connect" onClick={connectWallet}>
          Connect Wallet
        </button>
      </header>
    </div>
  );
}
export default App;

You can check this live project link, The final UI looks like this:

Web3Modal UI

Error Resolve:

Version Issue
An issue arises when you are using React version 18, it's using react-scripts 5.0.0 but 
Web3Modal uses 4.0.3 for now, so we also solve this problem by changing the react-scripts version to 4.0.3 in the package.json file of our project. After changing, you have to again write npm install in the terminal to update the react project dependencies accordingly.

Conclusion:

So we have finally completed the tutorial, I hope you easily understood how to add Web3Modal to our React project. I also told you the error which I got due to React version 18, if you face any more issues, you can comment below, I will try my best to solve your problems as soon as possible.

More resources:

No comments:

Post a Comment

Bottom Ad [Post Page]