How to connect ReactJS with MetaMask ? - GeeksforGeeks (2024)

To Connect React JS with MetaMask is important while making Web 3 applications, It will be done with Meta mask wallet which is the most used browser tool for sending and receiving signed transactions .

MetaMask is a crypto wallet and a gateway to blockchain DAPP. It is used to connect our app to web3. It is just a Chrome extension that is used to access and interact with the Ethereum blockchain. Its features support tokens and digital assets in the Ethereum ecosystem. It is also used as a primary wallet to store the balance in Ethereum.

For connection, we are using ethers.js, in order to connect to the Ethereum wallet.

Approach to connect React JS with MetaMask

We will connect MetaMask to React using Ether library which can be used to initialize the authentication using MetaMask wallet browser extention. Then a request will be made to acces the account info e.g. current balance, last transections etc.

Steps to create React Application

Step 1: Creating a react project with CLI

npx create-react-app eth_app

Step 2: Move to the project directory

cd eth_app

Step 3: Install these packages to run the application

npm i react-bootstrap bootstrap [email protected]

Project Structure:

How to connect ReactJS with MetaMask ? - GeeksforGeeks (1)

The updated dependencies in package.json file will look like:

{
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"bootstrap": "^5.3.2",
"ethers": "^5.7.2",
"react": "^18.2.0",
"react-bootstrap": "^2.9.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
}

Example: Initiallize metamask authentication usign browser extention when clicked on Connet button.

JavaScript
// Filename - App.js// Importing modulesimport React, { useState } from "react";import { ethers } from "ethers";import "./App.css";import { Button, Card } from "react-bootstrap";import "bootstrap/dist/css/bootstrap.min.css";function App() { // usetstate for storing and retrieving wallet details const [data, setdata] = useState({ address: "", Balance: null, }); // Button handler button for handling a // request event for metamask const btnhandler = () => { // Asking if metamask is already present or not if (window.ethereum) { // res[0] for fetching a first wallet window.ethereum .request({ method: "eth_requestAccounts" }) .then((res) => accountChangeHandler(res[0]) ); } else { alert("install metamask extension!!"); } }; // getbalance function for getting a balance in // a right format with help of ethers const getbalance = (address) => { // Requesting balance method window.ethereum .request({ method: "eth_getBalance", params: [address, "latest"], }) .then((balance) => { // Setting balance setdata({ Balance: ethers.utils.formatEther(balance), }); }); }; // Function for getting handling all events const accountChangeHandler = (account) => { // Setting an address data setdata({ address: account, }); // Setting a balance getbalance(account); }; return ( <div className="App"> {/* Calling all values which we  have stored in usestate */} <Card className="text-center"> <Card.Header> <strong>Address: </strong> {data.address} </Card.Header> <Card.Body> <Card.Text> <strong>Balance: </strong> {data.Balance} </Card.Text> <Button onClick={btnhandler} variant="primary" > Connect to wallet </Button> </Card.Body> </Card> </div> );}export default App;

Step to run the application: Open the terminal and type the following command.

npm start

Output:Open the browser and our project is shown in the URLhttp://localhost:3000/



Please Login to comment...

How to connect ReactJS with MetaMask ? - GeeksforGeeks (2024)
Top Articles
How Much Yarn To Crochet A King Size Blanket
5 Common Smart Home Device Problems and Their Solutions | Moving & Improving
Unit 30 Quiz: Idioms And Pronunciation
Chicago Neighborhoods: Lincoln Square & Ravenswood - Chicago Moms
Dollywood's Smoky Mountain Christmas - Pigeon Forge, TN
Dew Acuity
Top Scorers Transfermarkt
Phone Number For Walmart Automotive Department
Call Follower Osrs
27 Places With The Absolute Best Pizza In NYC
Noaa Weather Philadelphia
Produzione mondiale di vino
Music Archives | Hotel Grand Bach - Hotel GrandBach
Monticello Culver's Flavor Of The Day
Bill Devane Obituary
Lantana Blocc Compton Crips
Thayer Rasmussen Cause Of Death
Brutál jó vegán torta! – Kókusz-málna-csoki trió
Premier Reward Token Rs3
Lesson 8 Skills Practice Solve Two-Step Inequalities Answer Key
Echat Fr Review Pc Retailer In Qatar Prestige Pc Providers – Alpha Marine Group
Everything We Know About Gladiator 2
Vipleaguenba
Lcwc 911 Live Incident List Live Status
Nordstrom Rack Glendale Photos
Walgreens Tanque Verde And Catalina Hwy
Gopher Hockey Forum
Ubg98.Github.io Unblocked
Is A Daytona Faster Than A Scat Pack
Diakimeko Leaks
Bjerrum difference plots - Big Chemical Encyclopedia
Play It Again Sports Norman Photos
Costco Gas Hours St Cloud Mn
Ihub Fnma Message Board
Sadie Sink Reveals She Struggles With Imposter Syndrome
Craigslist Comes Clean: No More 'Adult Services,' Ever
Amazing Lash Bay Colony
Rogold Extension
Missing 2023 Showtimes Near Mjr Southgate
Vlocity Clm
The Ultimate Guide to Obtaining Bark in Conan Exiles: Tips and Tricks for the Best Results
Roch Hodech Nissan 2023
Kokomo Mugshots Busted
24 slang words teens and Gen Zers are using in 2020, and what they really mean
Rogers Centre is getting a $300M reno. Here's what the Blue Jays ballpark will look like | CBC News
Scarlet Maiden F95Zone
Craigslist Woodward
Kaamel Hasaun Wikipedia
Walmart Listings Near Me
Mytmoclaim Tracking
WHAT WE CAN DO | Arizona Tile
One Facing Life Maybe Crossword
Latest Posts
Article information

Author: Corie Satterfield

Last Updated:

Views: 5890

Rating: 4.1 / 5 (62 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Corie Satterfield

Birthday: 1992-08-19

Address: 850 Benjamin Bridge, Dickinsonchester, CO 68572-0542

Phone: +26813599986666

Job: Sales Manager

Hobby: Table tennis, Soapmaking, Flower arranging, amateur radio, Rock climbing, scrapbook, Horseback riding

Introduction: My name is Corie Satterfield, I am a fancy, perfect, spotless, quaint, fantastic, funny, lucky person who loves writing and wants to share my knowledge and understanding with you.