This page looks best with JavaScript enabled

Create Your First BlockChain Ethereum DAPP With React

 ·  ☕ 7 min read  ·  ✍️ Adesh

We’ll create the Ethereum smart contract first, deploy it to the blockchain and connect it with our React app.

Ethereum Smart Contract

When coding the ethereum blockchain, we actually write code, called Smart Contract with Solidity. We program and debug it on our own development environment (a personal blockchain run in local computer). Once it is ready, we deployed it to the public ethereum testnet (there are multiple ones), and finally launch it to the mainnet.

Contract deployment costs ether. We can get ether for free in testnet, but have to pay a small amount of ether (read money) to deploy contracts in the mainnet.

Setting up Ethereum BlockChain Project

For this stack, we’ll be using the Truffle.js suite of development tools. First, install Truffle, if not on your machine already.

I am going to use the existing smart contract code which I have created in my previous blog. In this blog, I have explained about setting up and using the ethereum blockchain using Truffle. Please click the below link to read more about this.

Deploy Your First Smart Contract With Truffle

This is our Hello smart contract.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
pragma solidity >=0.4.21 <0.7.0;

contract Hello {
    string greeting;

    constructor() public {
        greeting = "hello";
    }

    function getGreeting() public view returns(string memory) {
        return greeting;
    }

    function setGreeting(string memory _greeting) public {
        greeting = _greeting;
    }
}

So, we have two smart contract functions getGreeting() and setGreeting() in Hello.sol file.

We have our smart contract for the project. We can compile our code. We do so with Truffle.

1
truffle compile

Deploying our smart contract

To deploy our smart contract, we will create our migration file for our Hello.sol (see the previous post).

Next, we create a local Ethereum testing network (testnet) and deploy our code locally. We do so again with Truffle. Start a development blockchain:

1
truffle develop

Truffle should display a host and port, as well as a set of accounts with their corresponding private keys.

Using this development environment, we migrate our contracts to this local testnet:

1
truffle migrate

OR

1
truffle migrate --reset

This will be our final ethereum smart contract project structure.

truffle project structure

Now, exit from truffle cli and create our React app.

1
.exit

Creating React App

Use create-react-app command to create your React app in your existing project.

1
npx create-react-app clientapp

It will create a clientapp folder in your HelloTruffle project.

We are going to install web3.eth library in our react app. The web3-eth package allows you to interact with an Ethereum blockchain and Ethereum smart contracts.

1
cd clientapp
1
npm install web3

Create The ABI Definition Of Your Smart Contract

In order to allow your JavaScript front-end to communicate with a Smart Contract, you need to create what’s referred to as the “ABI definition” of your contract.

The ABI of a given smart contract is created when a smart contract is compiled in Truffle. After a successful compilation, you will see a JSON file of the compiled contract in the folder /build/contracts.

In our Hello.json file, there should be a field named "abi" holding the contract’s ABI object, which is an array of objects for each function in a contract. We’ll copy that, and hold it in our client.

Hello contract compiled json file having abi info

Let’s create a smart contract ABI file named HelloAbi.js in clientapp/src folder.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
export const HelloAbi = [
  {
    inputs: [],
    payable: false,
    stateMutability: "nonpayable",
    type: "constructor"
  },
  {
    constant: true,
    inputs: [],
    name: "getGreeting",
    outputs: [
      {
        internalType: "string",
        name: "",
        type: "string"
      }
    ],
    payable: false,
    stateMutability: "view",
    type: "function"
  },
  {
    constant: false,
    inputs: [
      {
        internalType: "string",
        name: "_greeting",
        type: "string"
      }
    ],
    name: "setGreeting",
    outputs: [],
    payable: false,
    stateMutability: "nonpayable",
    type: "function"
  }
];

Importing dependencies in our React app

In App.js we’ll import web3 and our ABIs.

1
2
3
4
5
6
7
import React, { useState } from "react";
import Web3 from "web3";
import { HelloAbi } from "./HelloAbi.js";

import "./App.css";

const web3 = new Web3(Web3.givenProvider);

Given provider is the default Web 3 provider, a.k.a. smart contract compatible Ethereum wallet, provided by the user’s browser. In many cases, this may be the Metamask browser extension.

Creating Smart Contract Instance

In order to interact with our smart contract, we are going to use web3.eth.Contract. The web3.eth.Contract object makes it easy to interact with smart contracts on the ethereum blockchain. When you create a new contract object you give it the json interface of the respective smart contract and web3 will auto convert all calls into low level ABI calls over RPC for you.

This allows you to interact with smart contracts as if they were JavaScript objects.

new contract

Creates a new contract instance with all its methods and events defined in its json interface object.

1
2
const contractAddress = "0x0E5d74eEfb29999f5e6005aF329FB473d6ccb379";
const HelloContract = new web3.eth.Contract(HelloAbi, contractAddress);

Here we created contractAddress and HelloContract instance in App.js file.

Here is the complete App.js file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import React, { useState } from "react";
import Web3 from "web3";
import { HelloAbi } from "./HelloAbi.js";

import "./App.css";

const web3 = new Web3(Web3.givenProvider);

const contractAddress = "0xEe....."; //Contract Address
const HelloContract = new web3.eth.Contract(HelloAbi, contractAddress);

function App() {
  const [greeting, setGreeting] = useState(0);

  const setData = async e => {
    e.preventDefault();
    const accounts = await window.ethereum.enable();
    const account = accounts[0];
    const gas = await HelloContract.methods.setGreeting(greeting).estimateGas();
    const result = await HelloContract.methods
      .setGreeting(greeting)
      .send({ from: account, gas });
    console.log(result);
  };

  const getData = async e => {
    e.preventDefault();
    const result = await HelloContract.methods.getGreeting().call();

    console.log(result);
  };

  return (
    <div className="App">
      <header className="App-header">
        <form onSubmit={setData}>
          <label>
            Set Data:
            <input
              type="text"
              name="greeting"
              value={greeting}
              onChange={e => setGreeting(e.target.value)}
            />
          </label>
          <input type="submit" value="Set Data" />
        </form>
        <br />
        <button onClick={getData} type="button">
          Get Data
        </button>
      </header>
    </div>
  );
}

export default App;

Adding MetaMask to Chrome Browser

To interact with Ethereum through the app, we need a wallet that provides signatures for each smart contract action. For this example, we’ll use Metamask as our signature provider, however, more signature providers exist. Metamask is a browser extension that serves as an Ethereum wallet.

Once Metamask is installed on your browser, we configure it to our local testnet using the address Truffle provided. In our case, that address is found in the line Truffle Develop started at [http://127.0.0.1:9545/](http://127.0.0.1:9545/) . We go up to networks, click Custom RPC, and enter the URL provided by Truffle.

MetaMask truffle

Once we’ve added our testnet RPC, we import the accounts Truffle provided. Only one account is needed for this app, but Truffle provides ten accounts if you need to test more complex interactions. In this example, the private key 26db574a49ba302ed5763af2aff0f9b692db85fb63b2c8d6d6bed05fbdbb765b provided by Truffle is imported, containing 100 testnet Ether.

Click on the MetaMask circle and select the Import Account option from the menu.

MetaMask Account import

MetaMask Import screen

To get truffle keys, type truffle develop command and it will show 10 private keys. Use any private key. I am using my first private key to import this account. Enter your private key in the Import tab and click on the Import button.

Once imported, it will show below the account screen with 100 ETH.

Truffle account import

Running React app and do the transaction

Once everything is set up, run below command to run your react app in the Chrome browser.

1
npm run start

smart contract screen

Enter any text like Hello Test and press the Set Greeting button to initiate the ethereum transaction. It will show below MetaMask’s connect confirmation screen.

MetaMask connect request

Click on the Connect button to proceed. It will show the Gas Fee and Total transaction amount. Click on the Confirm button.

transaction gas fee

Once you click on the Confirm button, a transaction will happen, and it will be shown in your browser’s console window. It will show transaction detail like below.

MetaMask Transaction detail

transaction confirmation

Similarly, when you click on the Get Data button, it will show your data.

Share on

Adesh
WRITTEN BY
Adesh
Technical Architect