Web3.js

How do I integrate Web3js with React


Integrating Web3.js with React allows you to build decentralized applications (dApps) that interact with the Ethereum blockchain. Below is a detailed guide on how to set up your React application with Web3.js

Step 1: Set Up Your React Project

First, create a new React project using Create React App. Open your terminal and run:

npx create-react-app my-dapp

Navigate into your project directory:

cd my-dapp

Start the development server:

npm start

Step 2: Install Web3.js

Next, you need to install the Web3.js library. Run the following command in your project directory:

npm install web3

Step 3: Create a Web3 Instance

In your React application, you will need to create a Web3 instance to interact with the Ethereum blockchain. You can do this in your main component (e.g., App.js).

import React, { useEffect, useState } from 'react';
import Web3 from 'web3';
function App() {
    const [web3, setWeb3] = useState(null);
    useEffect(() => {
        const initWeb3 = async () => {
            if (window.ethereum) {
                const web3Instance = new Web3(window.ethereum);
                await window.ethereum.request({ method: 'eth_requestAccounts' });
                setWeb3(web3Instance);
            } else {
                alert('Please install MetaMask!');
            }
        };
        initWeb3();
    }, []);
    return (
        <div>
            <h1>My DApp</h1>
            {web3 ? <p>Web3 is connected!</p> : <p>Connecting to Web3...</p>}
        </div>
    );
}
export default App;

Step 4: Interacting with Smart Contracts

To interact with a smart contract, you need the contract's ABI (Application Binary Interface) and its deployed address. You can obtain these from your smart contract deployment process.

const contractABI = [ /* ABI goes here */ ];
const contractAddress = '0xYourContractAddress';
const contract = new web3.eth.Contract(contractABI, contractAddress);

Now you can call functions on your smart contract. For example, to call a function named getValue:

const getValue = async () => {
    const value = await contract.methods.getValue().call();
    console.log(value);
};

Step 5: Sending Transactions

To send a transaction to your smart contract, you can use the following code:

const sendValue = async (newValue) => {
    const accounts = await web3.eth.getAccounts();
    await contract.methods.setValue(newValue).send({ from: accounts[0] });
};

Conclusion

By following these steps, you can successfully integrate Web3.js with your React application. This setup allows you to build powerful decentralized applications that can interact with the Ethereum blockchain.

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.