{"id":404,"date":"2022-03-21T17:05:55","date_gmt":"2022-03-21T07:05:55","guid":{"rendered":"https:\/\/programmablewealth.com\/?p=404"},"modified":"2022-03-21T17:05:59","modified_gmt":"2022-03-21T07:05:59","slug":"ethersjs-react-tutorial","status":"publish","type":"post","link":"http:\/\/10.0.0.14:32768\/ethersjs-react-tutorial\/","title":{"rendered":"How to Get Started Using Ethers.js With React"},"content":{"rendered":"\n

React<\/a> is a front-end Javascript library that is widely adopted for building web applications.<\/p>\n\n\n\n

Ethers.js<\/a> is a web 3.0 library that can be used for interacting with smart contracts on the Ethereum blockchain and other Ethereum Virtual Machine (EVM) compatible blockchains.<\/p>\n\n\n\n

In this tutorial, I will cover how to use Ethers.js with React to build a front-end web application that can:<\/p>\n\n\n\n

  1. Connect to a Metamask wallet in the browser<\/li>
  2. Read the balance of the wallet<\/li>
  3. Access the current block of the Ethereum network<\/li>
  4. Listen to updates to the block of the Ethereum network<\/li>
  5. Read data from a smart contract<\/li>
  6. Make a write transaction to a smart contract via Metamask<\/li><\/ol>\n\n\n\n

    Creating a React Project with Create React App<\/h2>\n\n\n\n

    First, we will create a new React project using the create-react-app<\/a> utility.<\/p>\n\n\n\n

    If you don’t have the create-react-app utility on your computer, you can download it via npm with the following command.<\/p>\n\n\n\n

    npm install -g create-react-app<\/code><\/pre>\n\n\n\n

    We will create a new React project with the name react-ethersjs with the following command.<\/p>\n\n\n\n

    npx create-react-app react-ethersjs<\/code><\/pre>\n\n\n\n

    Once the project has been created, change the directory into your project and then you can test the app has been successfully created with the command<\/p>\n\n\n\n

    yarn start<\/code><\/pre>\n\n\n\n

    This should display your web application in a new browser tab.<\/p>\n\n\n\n

    \"\"<\/figure>\n\n\n\n

    How to Install Ethers.js<\/h2>\n\n\n\n

    Ethers.js is simple to install.<\/p>\n\n\n\n

    To install using yarn inside the root directory of your React project, run the command<\/p>\n\n\n\n

    yarn add ethers<\/code><\/pre>\n\n\n\n

    Alternatively, you can install Ethers.js with npm with the following command<\/p>\n\n\n\n

    npm install --save ethers<\/code><\/pre>\n\n\n\n

    How to Connect to Metamask using Ethers.js<\/h2>\n\n\n\n

    Metamask is a popular cryptocurrency wallet that is used in browsers as a browser extension or add-on.<\/p>\n\n\n\n

    It has the ability to interact with decentralized applications (DApps).<\/p>\n\n\n\n

    In order to connect a Metamask wallet to a React app, we will first create a new React component for connecting Metamask to the React app with Ethers.js.<\/p>\n\n\n