Connecting wallet to your dApp using Web3React

ยท

4 min read

Connecting wallet to your dApp using Web3React

This tutorial aims to give you a guide and teach you how to connect your wallet to your decentralized application using web3React. Web3React is a simple, maximally extensible, dependency minimized framework for building modern Ethereum dApps.

Getting Started

To get started, I'll create a new react application.

npx create-react-app web3-react-tutorial

Next, change into the new directory and install the dependencies:

cd web3-react-tutorial

npm install web3 @web3-react/core @web3-react/injected-connector @ethersproject/providers

Now run the code bellow to serve the application locally at localhost:3000.

npm start

hashnode-2.PNG

Now, create a wallet folder in the src folder, then create a connector.js file in the wallet folder. Then add this code below:

import { InjectedConnector } from '@web3-react/injected-connector'

export const injected = new InjectedConnector({
    supportedChainIds: [1, 3, 4, 5, 42, 56, 97, 1337]
})

The connector helps us to connect to the Metamask wallet.

Next, we'll need to set up the provider in the index.js file, then add the code below:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css'
import App from './App';
import { Web3ReactProvider } from '@web3-react/core'
import { Web3Provider } from '@ethersproject/providers'

function getLibrary(provider, connector) {
  return new Web3Provider(provider)
}

ReactDOM.render(
  <Web3ReactProvider getLibrary={getLibrary}>
    <App />
  </Web3ReactProvider>,
  document.getElementById('root')
);

In the code above, we set up the Web3 provider to have access to the global web3 object and hook, then we wrap <App /> inside <Web3ReactProvider> after passing getLibrary as a prop.

In the App.js, we'll create a button to connect to Metamask. We will also display the wallet address that our dApp is connected to.

import { useState } from "react"
import { useWeb3React } from '@web3-react/core'
import { injected } from "./wallet/connector"

function App() {
  const { active, account, library, connector, activate, deactivate } = useWeb3React();

  async function connectWallet() {
    try {
      await activate(injected)
    } catch (error) {
      console.log(error);
    }
  }

  return (
    <div>
      {!account && (<div className="btn-container">
        <button className="connect-btn" onClick={connectWallet}>
          Connect Wallet ๐Ÿ’ณ
        </button>
        {active ? <div className="text-center"> Connected with {account} </div> : <div className="text-center">Not Connected</div>}
      </div>)
      }
    </div>
  );
}

export default App;

Import the useWeb3React hook from @web3-react/core

import { useWeb3React } from '@web3-react/core'

Also, import the injected connector into the App.js file.

import { injected } from "./wallet/connectors";

Now, let's use the useWeb3React hook to get the values we would be using;

const { active, account, library, activate, deactivate } = useWeb3React()

  • active returns a boolean to let us know if the user has connected a wallet

  • account returns the wallet address that is connected

  • library provides us with the function to interact with the smart contract

  • activate is the function that we call in order to authenticate with the user's wallet

  • deactivate is the function to disconnect from the user's wallet

Inside the connectWallet function, use the activate function with the injected connector as an argument. The activate function helps the user to connect to the MetaMask wallet.

async function connectWallet() {
    try {
      await activate(injected)
    } catch (error) {
      console.log(error);
    }
  }

To bind the connectWallet functionality;

<button className="connect-btn" onClick={connectWallet}>
  Connect Wallet ๐Ÿ’ณ
</button>

When the user clicks the connect wallet button, the user will be able to authenticate. hashnode-7.PNG

To disconnect the wallet, add the disconnect button and disconnectWallet function in your App.js

function disconnectWallet() {
  try {
    deactivate()
  } catch (error) {
    console.log(error);
  }
}

<div className="btn-container">
  <button className="connect-btn" onClick={disconnectWallet}>
    Disconnect Wallet ๐Ÿ’ณ
  </button>
</div>

Right now, your App.js should look like the code below

import React from "react"
import { useWeb3React } from '@web3-react/core'
import { injected } from "./wallet/connector"

function App() {
  const { active, account, library, connector, activate, deactivate } = useWeb3React();

  async function connectWallet() {
    try {
      await activate(injected)
    } catch (error) {
      console.log(error);
    }
  }
  function disconnectWallet() {
    try {
      deactivate()
    } catch (error) {
      console.log(error);
    }
  }

  return (
    <div>
      {!active ? (<div className="btn-container">
        <button className="connect-btn" onClick={connectWallet}>
          Connect Wallet ๐Ÿ’ณ
        </button>
      </div>) :
        (<div className="btn-container">
        <button className="connect-btn" onClick={disconnectWallet}>
          Disconnect Wallet ๐Ÿ’ณ
        </button>
      </div>)
      }

      {active ? <div className="text-center"> Connected with {account} </div> : <div className="text-center">Not Connected</div>}
    </div>

  );
}

export default App;

Add the styles below in your index.css file.

.btn-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  font-size: 16px;
}

.text-center {
  text-align: center;
  margin-top: 10px;
}

.connect-btn {
  background-color: gray;
  padding: 12px 20px;
  color: white;
  outline: none;
  border: 0;
  border-radius: 4px;
}

Users can now connect and disconnect their wallets and then proceed to interact with your smart contracts.

hashnode-8.PNG

Conclusion

We have discussed web3-react and how to connect your decentralised applications (dApps) to your wallet using web3-react.

Learning blockchain and Web3 now is like learning how to use the internet in the 90s, it is still at its early stage. Blockchain technology is now being adopted every day, I believe software developers need to be equipped with the necessary tools

Hope youโ€™ve learnt something new, the whole code is being hosted on this GitHub Link.

Feel free to connect with me on LinkedIn and Twitter.