DEV Community

fangjun
fangjun

Posted on • Updated on

Web3-UI Working Note #01: Install & Example

A handy Web3 UI Component library is mostly needed when Web2 developers dive into Web3 space. Web3-UI is an ambitious project by DeveloperDAO which is still in development. It focuses on EVM compatible blockchains.

I have used several frameworks, packages, scaffolds and tools and I strongly hope that Web3-UI can be the new basic building block for the future. I will write a series of notes to record my first impression with this framework as it grows up.

1. What is Web3-UI and Why?

The about section in its Github repository (https://github.com/Developer-DAO/web3-ui) introduces itself concisely:

A React UI library for Web3

It is based on works by Dhaiwat10 and sixfootsixdesigns.

There is a DeveloperDAO RFC documents by Dhaiwat10 explaining the motivation:

Right now, there is no UI library that is crafted specifically for web3. Everyone has to craft their own internal solutions. Most of these internal solutions aren’t well-tested, well-documented or well-functioning. This is because most teams don’t have the resources to invest in crafting a complete solution of their own.

Currently Web3-UI is still in development. It is incomplete, not well-documented and interwined with many other libraries and components. But the groundwork is already built. There are three packages in it:

  • Components
  • Core
  • Hooks

In the background, ethers.js is used. The ethers.js library is a Javascript library for interacting with the Ethereum Blockchain and its ecosystem. To be a web3 developer, ethers.js or web3.js is a very important tool.

Let's give Web3-UI a try.

(After typing the name "Web3-UI" several times in this note, I think it may change its name to "Web3UI" for writer's convenience. Well, I find that there is actually a package called web3uikit.)


Note: What do we want a Web3 UI to do?

  1. Connect Wallet

  2. Read blockchain (Query data from blockchain or smart contract)

  3. Write blockchain (Change data in blockchain or smart contract)

  4. Keep data synced to blockchain and smart contract

For data sync between front-end and blockchain, Drizzle by Truffle Suite is good. Web3-UI should consider including this functionality. There is a good explanation about "How Data Stays Fresh".


2. Installation and First Impression

I will try Web3-UI in a next.js project. In this first note, I will only cover wallet connect component and some basic components to read data from blockchain. The following steps are adapted from the web3-ui documents and examples.

I will try reading from and writing to smart contract later. To do that, we will need to deal with smart contract ABI(Apaplication Binary Interface).

STEP 1: create next-app

Create Next.js APP "my3app" from command line:

yarn create next-app --typescript
Enter fullscreen mode Exit fullscreen mode

We can run it on localhost:3000:

yarn dev
Enter fullscreen mode Exit fullscreen mode

STEP 2: Install Web3-UI package

Go to my3app directory and install the Web3-UI package:

cd my3app
yarn add @web3-ui/core
Enter fullscreen mode Exit fullscreen mode

STEP 3: Setup Provider

Import Provider and NETWORKS from @web3-ui/core component.

// _app.tsx (or the root of your app)
import { Provider,NETWORKS } from '@web3-ui/core';

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <Provider network={NETWORKS.mainnet}>
      <Component {...pageProps} />
    </Provider>
  )
}
Enter fullscreen mode Exit fullscreen mode

Documents can be found at: https://github.com/Developer-DAO/web3-ui/blob/main/packages/core/README.md

STEP 4: Using ConnectWallet Component and Hook

Add account.tsx:

// pages/account.tsx
import { ConnectWallet, useWallet } from '@web3-ui/core';

function Account() {
  const { connection } = useWallet();

  return (
    <div style={{  margin: 'auto', width: '50%'}}>
      <ConnectWallet /> 
      <div>Address / ENS:{connection.ens || connection.userAddress}</div>
    </div>
  );
}

export default Account;
Enter fullscreen mode Exit fullscreen mode

There are two components in this page: ConnectWallet Button and a text to display ENS or address.

You can visit this page at: http://localhost:3000/account

Usage:

  • Click the button "Connect Wallet", choose Metamask or WalletConnect and connect.

  • ENS or address is displayed and Button is also changed to display the Address.

If you have an ENS with your address, it will first display the address and then ENS when ENS is returned.


3. Read blockchain and NFTGallery component

There are several samples in the repo. We adapt codes to display NFTs of an address here.

To query data from blockchain, users usually need to go through three steps:

  • Connect wallet
  • Input and Query
  • Get the results displayed.

To read blockchain, a connected wallet is not needed. But we asked users to connect wallet first here as we will add writing blockchain features later. If wallet is not connected, the user won't be able to click the submit button.

Chakra UI is used here. "Chakra UI is a simple, modular and accessible component library that gives you the building blocks you need to build your React applications."

Currently, Chakra UI is also used in the package. Perhaps we may change that to allow users of web3-UI package to choose their own favorite one.

Add shownft.tsx (We take code segments from web3-ui/example/nextjs to finish our first page with Web3-UI.):

// pages/shownft.tsx
import React, {ReactElement, useEffect, useState } from 'react';
import {Container,Stack,Input,Button,Heading,Text} from '@chakra-ui/react';
import { useWallet, ConnectWallet } from '@web3-ui/core';
import { NFTGallery } from '@web3-ui/components';

export default function Home() {
  const [address, setAddress] = useState('');
  const [nftGallery, setNftGallery] = useState<ReactElement|null>(null);
  const { correctNetwork, switchToCorrectNetwork, connected, provider } =
    useWallet();

  useEffect(() => {
    console.log('correctNetwork', correctNetwork);
  }, [correctNetwork]);

  return (
    <Container>
      <ConnectWallet />
      {!correctNetwork && (
        <Button onClick={switchToCorrectNetwork}>Switch to Mainnet.</Button>
      )}

      <Stack p={3}>
        <Heading>Demo</Heading>
        <Text>Type in an address to view their NFTs</Text>
        <Input
          placeholder="Address"
          value={address}
          onChange={(e) => setAddress(e.target.value)}
        />
        <Button
          disabled={!connected}
          onClick={() =>
            setNftGallery(
              <NFTGallery
                address={address}
                gridWidth={2}
                web3Provider={provider}
              />
            )
          }
        >
          {connected ? 'Submit' : 'Connect your wallet first!'}
        </Button>
        {nftGallery}
      </Stack>
    </Container>
  );
}

Enter fullscreen mode Exit fullscreen mode

Some explanations on front-end components of this page:

  • Wallet Connect Button (and switch to mainnet checking)
  • Address text input and submit
  • NFTGallary component to display NFT

To make this front-end page better, we may check the address beforehand.

NFTGallary uses Opensea API to fetch NFTs of an address:

fetch("https://api.opensea.io/api/v1/assets?owner=".concat(resolvedAddress))
Enter fullscreen mode Exit fullscreen mode

In sum, Web3-UI is a good start to a complete and useful UI component library for web3. I will play with Web3-UI and write more notes.


Discussion (0)