Transitioning from Frontend Development to Web3 with React | dApps

Daniel Mark John
4 min readMar 29, 2023

--

Introduction

As the world of blockchain technology continues to grow and evolve, more developers are becoming interested in the Web3 ecosystem. If you are a frontend developer experienced with React, you already have a solid foundation to dive into this space. In this article, we will discuss how you can leverage your React skills to build Web3 applications and provide a step-by-step guide with code examples. We will also conclude with some advice for frontend developers looking to transition into the Web3 space.

Getting Started with Web3

First, let’s understand what Web3 is. Web3 refers to the decentralized web built on blockchain technology, particularly Ethereum. It enables developers to create decentralized applications (dApps) that interact with smart contracts, allowing users to have more control over their data and assets.

To get started with Web3 development in React, you will need a few tools and libraries:

  1. Node.js
  2. MetaMask browser extension
  3. web3.js or ethers.js library
  4. Truffle or Hardhat for smart contract development and deployment (optional)

Creating a Simple React App with Web3

In this example, we will use web3.js to interact with Ethereum blockchain. First create a new React app using the Create React App CLI:

npx create-react-app web3-react-example
cd web3-react-example

Next, install the web3.js library:

npm install web3

Now, let’s create a simple React component to connect to an Ethereum wallet (e.g., MetaMask) and fetch the user’s account balance:

  1. First, import the necessary dependencies:
import React, { useState, useEffect } from "react";
import Web3 from "web3";

2. Create a functional React component called Web3Example:

const Web3Example = () => {
const [account, setAccount] = useState("");
const [balance, setBalance] = useState(0);

// ... code for useEffect and other functions

return (
<div>
<h1>Web3 React Example</h1>
<p>Account: {account}</p>
<p>Balance: {balance} ETH</p>
</div>
);
};

3. Connect to MetaMask and fetch the user’s account and balance:

useEffect(() => {
async function connectToMetaMask() {
if (window.ethereum) {
try {
// Request account access
await window.ethereum.request({ method: 'eth_requestAccounts' });

// Create a new Web3 instance
const web3 = new Web3(window.ethereum);

// Fetch account and balance
const accounts = await web3.eth.getAccounts();
const account = accounts[0];
const balance = await web3.eth.getBalance(account);

// Update state
setAccount(account);
setBalance(web3.utils.fromWei(balance, "ether"));
} catch (error) {
console.error("Error connecting to MetaMask:", error);
}
} else {
alert("Please install MetaMask to use this app!");
}
}

connectToMetaMask();
}, []);

This code initializes a new Web3 instance, requests account access from MetaMask, and retrieves the user’s account and balance. The balance is converted from wei (the smallest unit of ether) to ether using the web3.utils.fromWei() function.

Now you have a simple React app that connects to MetaMask and fetches the user’s Ethereum account balance.

Let’s expand this app to interact with a smart contract. For this example, we will use a simple contract called “Counter” which allows users to increment and retrieve a stored value.

  1. Deploy the smart contract: You can use a service like Remix to deploy the following Counter smart contract to the Ethereum network (Ropsten or Rinkeby testnet is recommended for testing):
pragma solidity ^0.8.0;

contract Counter {
uint256 private count;

function increment() public {
count += 1;
}

function getCount() public view returns (uint256) {
return count;
}
}

2. After deploying the contract, note down the contract’s address.

3. Add web3.js and update the App.js to interact with the smart contract:

import React, { useState, useEffect } from "react";
import Web3 from "web3";

const CounterABI = [
// ABI of your deployed Counter contract
];

const App = () => {
const [web3, setWeb3] = useState(null);
const [account, setAccount] = useState(null);
const [balance, setBalance] = useState(0);
const [counter, setCounter] = useState(null);
const [count, setCount] = useState(0);

useEffect(() => {
(async () => {
if (window.ethereum) {
try {
await window.ethereum.request({ method: "eth_requestAccounts" });
const web3Instance = new Web3(window.ethereum);
const accounts = await web3Instance.eth.getAccounts();
setAccount(accounts[0]);

const ethBalance = await web3Instance.eth.getBalance(accounts[0]);
setBalance(web3Instance.utils.fromWei(ethBalance));

const counterContract = new web3Instance.eth.Contract(CounterABI, "YOUR_CONTRACT_ADDRESS");
setCounter(counterContract);

const initialCount = await counterContract.methods.getCount().call();
setCount(initialCount);
} catch (error) {
console.error("Error initializing web3:", error);
}
} else {
alert("Please install MetaMask!");
}
})();

}, []);

async function incrementCounter() {
if (counter) {
await counter.methods.increment().send({ from: account });
const updatedCount = await counter.methods.getCount().call();
setCount(updatedCount);
}
}

return (
<div>
<h1>Web3 React App</h1>
<p>Account: {account}</p>
<p>Balance: {balance} ETH</p>
<h2>Counter</h2>
<p>Current Count: {count}</p>
<button onClick={incrementCounter}>Increment Counter</button>
</div>
);
};

export default App;

Replace `YOUR_CONTRACT_ADDRESS` with the address of the deployed contract and the `CounterABI` with the contract’s ABI. Now your React app can interact with the smart contract. Users can increment the counter by clicking the “Increment Counter” button, and the app will display the updated count.

Advice for Frontend Developers Transitioning to Web3

  1. Learn Solidity: Understanding the basics of smart contract development using Solidity will help you design better interactions between your frontend application and the blockchain.
  2. Understand Blockchain Concepts: Familiarize yourself with the fundamentals of blockchain technology, such as decentralized networks, consensus mechanisms, and cryptographic principles.
  3. Engage in the Community: Join developer forums, attend workshops, or participate in hackathons to expand your knowledge and network with other Web3 developers.
  4. Stay Updated: As the Web3 ecosystem is rapidly evolving, keep yourself updated with the latest tools, libraries, and best practices in the field.
  5. Experiment and Learn: Building small-scale dApps or contributing to open-source projects will help you gain practical experience and improve your skills in Web3 development.

Conclusion

As a frontend developer experienced with React, you already have a strong foundation to transition into the Web3 space. By leveraging your existing skills and expanding your knowledge of blockchain technology and smart contract development, you can build engaging, decentralized applications. This exciting and rapidly growing field offers numerous opportunities for developers to innovate and make a lasting impact on the future of the web.

--

--

Daniel Mark John
Daniel Mark John

No responses yet