Create a dapp using Truffle and React
Create a dapp tutorial
In this tutorial, we'll deploy a simple smart contract and build a Web3 frontend using React.
The Web3 frontend integrates with the smart contract to allow you to read from and write to the Ethereum blockchain.

Prerequisites

Use MetaMask or similar to create an Ethereum wallet for testing purposes.

Deploy the smart contract

1. Install Truffle

Truffle is a smart contract development tool and testing framework for blockchain networks.
Install Truffle globally using the Node.js package manager:
1
npm install -g truffle
Copied!

2. Fund your Ethereum account

Use a faucet to load testnet ETH on your Ethereum account for the Ropsten network.
You have to create an account to get to the faucet.

3. Create a project directory

Create a new project directory from the command line:
1
mkdir simple-storage
Copied!
cd into the new directory:
1
cd simple-storage
Copied!

4. Create a Truffle project

Create a bare Truffle project which generates the required directory structure to test and deploy contracts:
1
truffle init
Copied!
Truffle creates the following directory structure for your project:

5. Install hdwallet-provider

hdwallet-provider is a separate package that signs transactions for addresses derived from a 12 or 24-word mnemonic.
By default, the hdwallet-provider uses the first address generated from the mnemonic. However, this is configurable.
Infura does not manage your private keys, meaning it cannot sign transactions on your behalf.
Run the following command to install hdwallet-provider:
1
npm install @truffle/hdwallet-provider
Copied!
For more information, refer to the Truffle hdwallet-provider repository.
You can also use the Truffle Dashboard to allow MetaMask to sign your transactions.

6. Create the .env file

Install the dotenv package.
1
npm install dotenv
Copied!
Create a file named .env in your project directory to store the project and Ethereum account details.
The following example .env file includes the MetaMask secret recovery phrase. Refer to the MetaMask instructions on how to reveal a secret recovery phrase. If using a network other than Ropsten, ensure you update INFURA_API_URL accordingly.
1
INFURA_API_URL = "https://ropsten.infura.io/v3/<Your-Project-ID>"
2
MNEMONIC = "<Your-MetaMask-Secret-Recovery-Phrase>"
Copied!
Ensure you replace the following values in the .env file:
  • <Your-Project-ID> with the Project ID of the Ethereum project.
  • <Your-MetaMask-Secret-Recovery-Phrase> with the mnemonic of your MetaMask wallet. This phrase is used by the Truffle hdwallet-provider to sign transactions.
Never disclose your secret recovery phrase. Anyone with your recovery phrase can steal any assets held in your wallet.

7. Create a smart contract

Using an editor, create a smart contract in the contracts/ directory. In this example, we'll create a basic contract called SimpleStorage.sol.
1
pragma solidity >=0.5.8;
2
3
contract SimpleStorage {
4
uint256 storedData;
5
6
function set(uint256 x) public {
7
storedData = x;
8
}
9
10
function get() public view returns (uint256) {
11
return storedData;
12
}
13
}
Copied!

8. Configure the Truffle settings

Configure the truffle-config.js file to use the HDWalletProvider and include the required configuration to deploy to the network (Ropsten in this example). Find the truffle-config.js file in your project's root directory. Delete the contents of the file, and replace it with the following:
1
require('dotenv').config();
2
const HDWalletProvider = require('@truffle/hdwallet-provider');
3
const { INFURA_API_URL, MNEMONIC } = process.env;
4
5
module.exports = {
6
networks: {
7
development: {
8
host: "127.0.0.1",
9
port: 8545,
10
network_id: "*"
11
},
12
ropsten: {
13
provider: () => new HDWalletProvider(MNEMONIC, INFURA_API_URL),
14
network_id: 3,
15
gas: 5500000
16
}
17
}
18
};
Copied!
Refer to the Truffle documentation for more information about configuring the Truffle settings.

9. Compile the smart contract

Navigate to the project's root directory and run the following:
1
truffle compile
Copied!
If successful, you'll see output similar to:
1
Compiling your contracts...
2
===========================
3
> Compiling ./contracts/Migrations.sol
4
> Compiling ./contracts/SimpleStorage.sol
5
> Artifacts written to /Users/bgravenorst/simple-storage/build/contracts
6
> Compiled successfully using:
7
- solc: 0.5.16+commit.9c3226ce.Emscripten.clangls
Copied!
Compiled files go in the build/contracts/ directory, relative to your project root. Refer to the Truffle documentation for more information about the compilation process.

10. Create the deployment script

Scripts that deploy smart contracts are located in the migrations/ directory and are numbered. In the migrations/ directory, create a file called 2_deploy_contract.js.
Truffle requires a migration contract in order to use the migrations feature. The Migration.sol and associated deployment file (1_initial_migration.js) are created automatically when creating your Truffle project.
Add the following code to the 2_deploy_contract.jsfile:
1
const SimpleStorage = artifacts.require("SimpleStorage.sol");
2
3
module.exports = function(deployer) {
4
deployer.deploy(SimpleStorage);
5
};
Copied!

11. Deploy the smart contract

Run the migration command to deploy the smart contract to the Ethereum network:
1
truffle migrate --network ropsten
Copied!
If successful you'll see a response similar to the following:
Response
Use a block explorer like Etherscan to view transaction details by searching for the transaction hash or contract address for example.

Build the Web3 frontend

We'll use React to build the Web3 frontend that will communicate with the deployed smart contract.

1. Create a project directory

Use the npx command to create a React project boilerplate and a directory named storage-lab:
1
npx create-react-app storage-lab
Copied!
The command sets up your development environment with the latest JavaScript features, and optimizes your app for production.
cd into the new directory:
1
cd storage-lab
Copied!

2. Install Web3.js

The Web3.js library interacts with the Ethereum network.
You can also use the ether.js library to interact with the Ethereum network.
1
npm install web3
Copied!

3. Copy your smart contract into the new directory

Copy the smart contract project directory you created previously (simple-storage) into the React project directory. The project directory should now look as follows:
1
storage-lab
2
├── README.md
3
├── node_modules
4
├── package-lock.json
5
├── package.json
6
├── public
7
├── simple-storage
8
└── src
Copied!

4. Create a file containing the ABI information

The Application Binary Interface (ABI) is the standard way to interact with contracts in the Ethereum ecosystem.
We'll create a JavaScript file to enable the Web3 frontend to communicate with the smart contract deployed earlier via the smart contract's ABI.
While there are more elegant ways to get the frontend and contract to communicate, we'll do it manually in this tutorial for educational purposes.
When we compiled our smart contract earlier, it created a JSON file named SimpleStorage.json inside of the Truffle project's build/contracts/ directory. Copy the abi object from the JSON file and reformat it so that we can import it into our app.
In the /src directory, create a folder named /abi, which will contain our abi.js file. The /src directory should look as follows:
1
src
2
├── App.css
3
├── App.js
4
├── App.test.js
5
├── abi
6
│   └── abi.js
7
├── index.css
8
├── index.js
9
├── logo.svg
10
├── reportWebVitals.js
11
└── setupTests.js
Copied!
Copy the ABI data from the JSON file into the abi.js file and reformat it as follows:
1
export const SimpleStorage = [
2
{
3
inputs: [
4
{
5
internalType: "uint256",
6
name: "x",
7
type: "uint256",
8
},
9
],
10
name: "set",
11
outputs: [],
12
stateMutability: "nonpayable",
13
type: "function",
14
},
15
{
16
inputs: [],
17
name: "get",
18
outputs: [
19
{
20
internalType: "uint256",
21
name: "",
22
type: "uint256",
23
},
24
],
25
stateMutability: "view",
26
type: "function",
27
constant: true,
28
},
29
];
Copied!

5. Update the App.js file

The src/App.js file is the highest level component in the React application structure.
Update the file to include the app logic and interface components.
Replace <CONTRACT-ADDRESS> with your smart contract address. To locate the contract address, view the address field in the SimpleStorage.json file inside of the build/contracts/ directory.
1
import React, { useState } from "react";
2
import { SimpleStorage } from "./abi/abi";
3
import Web3 from "web3";
4
import './App.css';
5
6
// Access our wallet inside of our dapp
7
const web3 = new Web3(Web3.givenProvider);
8
// Contract address of the deployed smart contract
9
const contractAddress = "<CONTRACT-ADDRESS>";
10
const storageContract = new web3.eth.Contract(SimpleStorage, contractAddress);
11
12
function App() {
13
// Hold variables that will interact with our contract and frontend
14
const [number, setUint] = useState(0);
15
const [getNumber, setGet] = useState("0");
16
17
const numberSet = async (t) => {
18
t.preventDefault();
19
const accounts = await window.ethereum.enable();
20
const account = accounts[0];
21
// Get permission to access user funds to pay for gas fees
22
const gas = await storageContract.methods.set(number).estimateGas();
23
const post = await storageContract.methods.set(number).send({
24
from: account,
25
gas,
26
});
27
};
28
29
const numberGet = async (t) => {
30
t.preventDefault();
31
const post = await storageContract.methods.get().call();
32
setGet(post);
33
};
34
35
return (
36
<div className="main">
37
<div className="card">
38
<form className="form" onSubmit={numberSet}>
39
<label>
40
Set your uint256:
41
<input
42
className="input"
43
type="text"
44
name="name"
45
onChange={(t) => setUint(t.target.value)}
46
/>
47
</label>
48
<button className="button" type="submit" value="Confirm">
49
Confirm
50
</button>
51
</form>
52
<br />
53
<button className="button" onClick={numberGet} type="button">
54
Get your uint256
55
</button>
56
{getNumber}
57
</div>
58
</div>
59
);
60
}
61
62
export default App;
Copied!

6. Update the stylesheet

In the App.css file, delete the boilerplate stylesheet and add the following custom stylesheet:
1
.main {
2
text-align: center;
3
display: flex;
4
justify-content: center;
5
background-color: #f2f1f5;
6
height: 100vh;
7
}
8
9
.card {
10
min-height: 50vh;
11
width: 50vw;
12
display: flex;
13
flex-direction: column;
14
align-items: center;
15
justify-content: center;
16
}
17
18
.form {
19
height: 20vh;
20
width: 20vw;
21
display: flex;
22
justify-content: space-evenly;
23
flex-direction: column;
24
}
25
26
.button {
27
width: 20vw;
28
height: 5vh;
29
}
Copied!

7. Run the Web3 frontend

If you are using create-react-app version >=5 you may run into issues building, such as:
1
Module not found: Error: Can't resolve 'crypto' in 'C:\Users\Username\Projects\testProject\client\node_modules\eth-lib\lib'
2
3
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
4
This is no longer the case. Verify if you need this module and configure a polyfill for it.
Copied!
This is because NodeJS polyfills are not included in the latest version of create-react-app. Follow these instructions to resolve the issue.
Run the Web3 frontend from the command line.
1
yarn start
Copied!

8. Use the dapp

In your dapp, enter a value in the Set your uint256 field and click Confirm.
The MetaMask app should open to allow you to pay the required gas fee.
Click Get your uint256 to retrieve the value.
Note that the read operation does not require you to pay gas. This is because it's not a state-changing operation.