0Pricing
Web3 & DApp Development Fundamentals · บทเรียน

React และเฟรมเวิร์ก Web3

ผสานเฟรมเวิร์กส่วนหน้า เช่น React เข้ากับไลบรารี Web3 เพื่อสร้างส่วนติดต่อผู้ใช้แบบไดนามิกสำหรับ DApps

React และเฟรมเวิร์ก Web3 เป็นบทเรียน Web3 & DApp Development Fundamentals ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 3 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Web3 & DApp Development Fundamentals และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Web3 & DApp Development Fundamentals มีบทเรียนทั้งหมด 3 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

DApps Need User Interfaces

Decentralized Applications (DApps) aren't just smart contracts running on a blockchain. Just like traditional apps, they need a user interface (UI) for people to interact with them.

This UI is what users see and click. It connects to their crypto wallet (like MetaMask) and communicates with the blockchain to display information or send transactions.

React for Dynamic UIs

React is a very popular JavaScript library for building modern user interfaces. It's known for its component-based architecture, where your UI is broken down into small, reusable pieces.

Using React helps developers create dynamic, responsive, and complex DApp front-ends more efficiently.

Web3 Libraries: The Blockchain Bridge

To make your React app talk to the Ethereum blockchain, you need a 'Web3 library'. These libraries act as a crucial bridge, translating your JavaScript code into blockchain-understandable commands.

  • Web3.js: A comprehensive and widely used library for interacting with the Ethereum blockchain.
  • Ethers.js: A modern, lightweight, and often preferred alternative to Web3.js, known for its clean API.

Setting Up a React Project

Let's start by creating a new React project. We'll use create-react-app, a common tool that sets up a new React application with a good default structure.

Open your terminal and run the following command:

npx create-react-app my-dapp-frontend

Installing a Web3 Library

After creating your React project and navigating into its directory, the next step is to install a Web3 library. For this lesson, we'll use Web3.js.

Run this command in your project's terminal:

npm install web3

Connecting to an Ethereum Provider

Your DApp needs a connection to the Ethereum network. This connection is typically provided by the user's browser wallet, such as MetaMask. MetaMask injects a global window.ethereum object into the browser.

We use this window.ethereum object to initialize our Web3.js instance, allowing our app to read from and write to the blockchain.

Code Demo: Initialize Web3

This React component initializes Web3.js when the component mounts. It checks for a MetaMask provider and attempts to connect, updating the UI based on the connection status.

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

function App() {
  const [web3, setWeb3] = useState(null);
  const [isConnected, setIsConnected] = useState(false);

  useEffect(() => {
    const initWeb3 = async () => {
      if (window.ethereum) {
        try {
          // Request account access
          await window.ethereum.request({ method: 'eth_requestAccounts' });
          const web3Instance = new Web3(window.ethereum);
          setWeb3(web3Instance);
          setIsConnected(true);
          console.log('Web3 connected!');
        } catch (error) {
          console.error('User denied or connection error:', error);
        }
      } else {
        console.log('MetaMask not detected. Install it!');
      }
    };
    initWeb3();
  }, []); // Runs once on component mount

  return (
    <div>
      <h1>DApp Frontend</h1>
      {isConnected ? (
        <p>Connected to Ethereum!</p>
      ) : (
        <p>Not connected. Please install MetaMask.</p>
      )}
    </div>
  );
}

export default App;

Fetching User Account Address

Once connected to the Ethereum provider, we can use our web3 instance to retrieve the user's connected wallet addresses. This is a fundamental step for any DApp that needs to display user-specific data or prepare for transactions.

We typically fetch the first account from the list returned by web3.eth.getAccounts().

Displaying Account in React State

To show the connected account address in our React application, we'll store it in React's state using the useState hook. This allows the UI to automatically update when the account is fetched.

Let's update our App.js to display the connected account:

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

function App() {
  const [web3, setWeb3] = useState(null);
  const [account, setAccount] = useState(null);
  const [isConnected, setIsConnected] = useState(false);

  useEffect(() => {
    const initWeb3 = async () => {
      if (window.ethereum) {
        try {
          await window.ethereum.request({ method: 'eth_requestAccounts' });
          const web3Instance = new Web3(window.ethereum);
          setWeb3(web3Instance);
          setIsConnected(true);

          const accounts = await web3Instance.eth.getAccounts();
          setAccount(accounts[0]); // Store the first account
          console.log('Connected account:', accounts[0]);

        } catch (error) {
          console.error('Connection error:', error);
          setAccount(null);
          setIsConnected(false);
        }
      } else {
        console.log('MetaMask not detected.');
        setAccount(null);
        setIsConnected(false);
      }
    };
    initWeb3();
  }, []); // Empty dependency array means this runs once on mount

  return (
    <div>
      <h1>My DApp</h1>
      {isConnected && account ? (
        <p>Connected account: <code>{account}</code></p>
      ) : (
        <p>Please connect your wallet.</p>
      )}
    </div>
  );
}

export default App;

Web3 Integration Check

Which of the following is the primary purpose of a Web3 library (like Web3.js or Ethers.js) in a React DApp?

Integrating React & Web3 Recap

Today, we took our first steps into building DApp front-ends! We learned that React is excellent for building dynamic UIs, and Web3 libraries like Web3.js are crucial for connecting these UIs to the Ethereum blockchain.

We covered how to set up a React project, install Web3.js, initialize a connection using the window.ethereum provider, and fetch the user's connected wallet address to display in our app.

This foundational knowledge is key to making your DApps interactive and user-friendly. Next, we'll dive deeper into handling wallet connections and transactions.

คำถามที่พบบ่อย

บทเรียน “React และเฟรมเวิร์ก Web3” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “React และเฟรมเวิร์ก Web3” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Web3 & DApp Development Fundamentals ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Web3 & DApp Development Fundamentals มีบทเรียนทั้งหมด 3 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “React และเฟรมเวิร์ก Web3”

ผสานเฟรมเวิร์กส่วนหน้า เช่น React เข้ากับไลบรารี Web3 เพื่อสร้างส่วนติดต่อผู้ใช้แบบไดนามิกสำหรับ DApps คุณปฏิบัติ Web3 & DApp Development Fundamentals ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Web3 & DApp Development Fundamentals หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Web3 & DApp Development Fundamentals บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 3 บทเรียน

บทเรียน “React และเฟรมเวิร์ก Web3” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Web3 & DApp Development Fundamentals นี้ได้ไหม

ได้ บทเรียน Web3 & DApp Development Fundamentals ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. React และเฟรมเวิร์ก Web3
  2. การผสานรวมกระเป๋าเงิน
  3. การจัดการธุรกรรมและเหตุการณ์
← กลับไปที่ Web3 & DApp Development Fundamentals