DEV Community

Cover image for Create connect wallet button with React + Web3.js + Bootstrap
Independence DEV
Independence DEV

Posted on • Updated on

Create connect wallet button with React + Web3.js + Bootstrap

I will teach you how to create a button that will interact with MetaMask to let the user connect their wallet on your app.

npx create-react-app wallet-connect
cd wallet-connect

Check the react-scripts version in package.json, the version need to be 4.0.3 to be compatible with web3.js

Run this command line to install everything we need :
yarn add web3 react-bootstrap bootstrap react-bootstrap-icons

add this line in index.js :

import 'bootstrap/dist/css/bootstrap.css';
Enter fullscreen mode Exit fullscreen mode

Final App.js file :

import React from 'react';
import Web3 from "web3";
import { Button } from 'react-bootstrap';
import { Wallet } from 'react-bootstrap-icons';
import './App.css';

class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      web3: null,
      currentAccount: null,
      ethBalance: 0,
      networkId: null
    };
  }

  componentDidMount = async () => {
    this.connectWalletHandler();
  };

  connectWalletHandler = async () => {
    try {
      const web3 = new Web3(Web3.givenProvider);
      this.setState({ web3: web3});
      const accounts = await web3.eth.requestAccounts();
      if (accounts.length !== 0) {
        const networkId = await web3.eth.net.getId();
        const ethBalance = await web3.eth.getBalance(accounts[0]);
        this.setState({currentAccount: accounts[0], ethBalance: Web3.utils.fromWei(ethBalance), networkId: networkId});
      } 
    } catch (error) {
      console.error(error);
    }
  }

  connectedWallet = () => {
    return (
      <div>
        <p>{parseFloat(this.state.ethBalance).toFixed(4)} ETH</p>
        <p>{this.state.currentAccount.slice(0,5)+'...'+this.state.currentAccount.slice(38,42)}<br />WALLET CONNECTED</p>
      </div>
    )
  }

  connectWalletButton = () => {
    return (
      <Button variant="outline-primary" onClick={() => this.connectWalletHandler()}><Wallet />&ensp;Connect wallet</Button>
    )
  }

  render() {
    return (
      <div className="App">
         {this.state.currentAccount ? this.connectedWallet() : this.connectWalletButton()}
      </div>
    );
  }
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)