Connect Metamask Wallet ( or any wallet to your ReactJS app

Connect Metamask Wallet ( or any wallet to your ReactJS app

Hello, in this post I’ll be showing how to use a library called web3-react in order to connect users to MetaMask or any wallet from your reactjs front end.

To start, I’ll just create a simple ReactJS application.

npx create-react-app web3-react-example

Now let’s add the connector. Inside of src folder, create folder by the name wallet, inside of it create a file name Connectors.jsx.

You can think of a connector as the thing connecting you to a certain wallet. So this one is for MetaMask, but there are others like the WalletConnect connector and the Portis connector.

Now import it in and simply export an injected connector object like so:

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

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

so, what are chain ids?

In simple words, every other testnet or mainnet blockchain have its chain id, like:

  1. Ethereum Mainnet: 1
  2. Polygon Mainnet: 137
  3. Görli: 5 etc

We are done with our connector.jsx, Next, we need to set up the provider.

In order to connect to wallets, we need to install the core dependency. Do that like so:

npm install @web3-react/core

You will also need either web3 or ethers:

npm install web3

Copy this below code and paste that into your index.js file, i will explain it one by one.a

// index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { Web3ReactProvider } from '@web3-react/core'
import Web3 from 'web3'

function getLibrary(provider) {
  return new Web3(provider)
}

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

reportWebVitals();

In the above code, i am importing Web3ReactProvider from @web3-react/core and Web3 from web3:

import { Web3ReactProvider } from '@web3-react/core'
import Web3 from 'web3'

After that i am creating a library:

function getLibrary(provider) {
  return new Web3(provider)
}

In the last step here, i wrapped my app inside of Web3ReactProvider and passed getLibrary in as a prop:

<Web3ReactProvider getLibrary={getLibrary}>
    <App />
  </Web3ReactProvider>

Now, go to App.js file:

import the injected connector:

import { injected } from './wallet/Connector';

Create a function and call it connect or whatever you want:

const connectMetamask= async () => {}

Set the button to call it on click:

<button onClick={connectMetamask} >Connect to MetaMask</button>

use the useWeb3React hook to get all the needed values:

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

We will not use all of these values, but I thought I’d show them just so you know about them. Here’s my explanations for each:

  • active: is a wallet actively connected right now?
  • account: the blockchain address that is connected
  • library: this is either web3 or ethers, depending what you passed in
  • connector: the current connector. So, when we connect it will be the injected connector in this example
  • activate: the method to connect to a wallet
  • deactivate: the method to disconnect from a wallet

Inside the connect function, use the activate function with the injected connector as an argument. This is what initiates the connection to the user’s MetaMask wallet:

const connectMetamask= async () => {
  try {
    await activate(injected)
  } catch (ex) {
    console.log(ex)
  }
}

However, at the moment, it would just connect but not show the user is connected visually. To do that, let’s do some simple conditional templating. If the user’s wallet is connected or active, then show their address. Otherwise, not connected:

{active ? <span>Connected with <b>{account}</b></span> : <span>Not connected</span>}

I’m also going to add a Disconnect button and function:

const disconnect = async () => {
  try {
    deactivate()
  } catch (ex) {
    console.log(ex)
  }
}
<button onClick={disconnect}>Disconnect</button>

Complete App.js file:

import './App.css';
import { injected } from './wallet/Connector';
import { useWeb3React } from "@web3-react/core"

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


  const connectMetamask = async () => {
    try {
      await activate(injected)
    } catch (ex) {
      console.log(ex)
    }
  }
  const disconnect = async () => {
    try {
      deactivate()
    } catch (ex) {
      console.log(ex)
    }
  }



  return (
    <div className="App">
      {!active && <button className='button glow-button' onClick={connectMetamask} >Connect to MetaMask</button>}
      <br />
      {active ? <span className='text'>Connected with <br /> <b>{account}</b></span> : <span span className='text'>Not connected</span>}
      <br />

      {active && <button className="button glow-button" onClick={disconnect}>Disconnect</button>}

    </div>

  );
}

export default App;