Web3 for Frontend Developers - Getting Started With Moralis Web3UI Kit Library

Web3 for Frontend Developers - Getting Started With Moralis Web3UI Kit Library

Learn the basics of the Web3UI Kit and how to build a well-designed, accessible user interface with speed!

ยท

10 min read

Introduction

The web3 ecosystem has prioritized back-end development of blockchain-based projects, while giving little to no contribution to the front-end stack.

The frontend is the development of the graphical user interface (UI) of an application. It describes how data is being presented and interacted with by the user on the browser; basically how the application performs in general.

In this article, we'll be discussing the Web3UI Kit, the first web3 front-end library, and weโ€™ll also build a dApp dashboard with it and Moralis React SDK.

Prerequisites

This article is project-based and you should have the following before continuing with this tutorial:

What We're Building With Web3UI Kit?

We'll build a dApp dashboard that displays all the NFTs and balance of a connected user on the Mainnet, Kovan, Rinkeby, Goerli, and the Ropsten Testnet.

After completing this tutorial, you'll have an understanding of how to set up and build a web3 frontend with Web3UI Kit components.

How It Works

Check out the basic flow of how our dApp dashboard will function below:

1. Users will log in by connecting their wallet:

Login page for the user to connect their wallet

2. Connected users will be redirected to their dashboard:

connected users can access the Web3 dApp dashboard and view their balances

Demo

Below, is a demo video of the dApp dashboard we're going to build in this tutorial:

Demonstration of Web3 dApp dashboard that we'll build with Web3UI Kit components and React, displaying a token balance of the connected user on the Mainnet, Kovan, Rinkeby, Goerli, and the Ropsten Testnet

You can also check out the live version of what we're building here.

What Is Web3UI Kit?

Moralis Web3UI Kit is the first web3 frontend library used to develop the dApp frontend

Web3UI Kit is an open source, lightweight, reusable web3 UI component. It was developed and currently maintained by the Moralis team. It's similar to the Web2 UI component library,Chakra UI and Material UI, but with more functionalities.

Web3UI Kit Components

The Moralis Web3UI Kit provides an easy to use user interface component that can make your dApp development faster.

Below, are some of the Web3UI Kits that weโ€™ll use to build our web3 dashboard:

1. BannerStrip

The Web3UI <BannerStrip /> is a top nav component that can be used to display an important notice to the user.

Ilustration of how Web3UI Kit BannerStrip works in React

2. NFTBalance

The Web3UI <NFTBalance /> is a UI component that fetches and displays all the NFTs owned by a particular address on a specified blockchain.

Illustration of how Web3UI Kit NFTBalance works in React

3. ConnectButton

The Web3UI <ConnectButton /> is an authentication button that allows the user to connect or disconnect their wallet from our dApp. Moralis will handle all the authentication logic under the hood.

Illustration of how Web3UI Kit ConnectButton works in React

4. useNotification

When an event or action takes place in our dApp, the Web3UI useNotification() hook can be used to emit and display a new notification to the user through the <Notification /> component.

Illustration of how Web3UI Kit useNotification works in React

5. Widget

The Web3UI <Widget /> component is a box that can be used to display a dataset label and its value.

Illustration of how Web3UI Kit Widget works in React

6. Todo

The Web3UI Kit provides a <Todo /> list UI component with CRUD functionality out of the box. You can implement a functional todo list in your dApp with only a few lines of code.

Illustration of how Web3UI Kit Todo works in React

7. Hero

The Web3UI kit <Hero> component can be used to quickly create a hero section for a dApp landing page.

Illustration of how Web3UI Kit Hero works in React

8. Credentials

The Web3UI <Credentials /> component can be used to toggle the visibility of sensitive data on the front end, such as passwords or tokens.

Illustration of how Web3UI Kit Credentials works in React

9. Typography

You can improve the font of your dApp with the Web3UI Kit <Typography /> component.

Illustration of how Web3UI Kit Typography works in React

You can check out the complete Web3UI Kit components list here.

Building the dApp Dashboard

In this section, we're going to combine all the Web3UI Kit components we've discussed above to build our web3 dashboard.

Step 1 - Installing Moralis Web3UI Kit in React

Run the command below to create a React app with yarn and Create React App (CRA):

yarn create react-app my-web3-dashboard

Navigate to the newly created folder with the command below:

cd my-web3-dashboard

Next, run the command below to install Moralis React SDK and Web3UI Kit:

yarn add moralis react-moralis web3uikit

Start your React server with the command below:

yarn start

Step 2 - Initializing Moralis SDK in React

After setting up your Moralis server and installing the Moralis SDK (see here), the next step is to establish a connection between our React app and our Moralis server, through the Moralis SDK.

Create a .env file at the root of your project and store your Moralis server details, like this:

REACT_APP_SERVER_URL=https://XXXXXX.usemoralis.com:2053/server
REACT_APP_APP_ID=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Replace the placeholders with your Moralis credentials. Next, we need to restart our server after updating the src/.env file.

Use the short key below to stop your server:

ctrl + c

Start your server again with:

yarn run start

Next, we'll update our App.js file with the code below:

import { NotificationProvider } from "web3uikit";
import { MoralisProvider } from "react-moralis";
import { Dashboard } from "./component/Dashboard";

function App() {
  return (
    <MoralisProvider
      serverUrl={process.env.REACT_APP_MORALIS_SERVER_URL}
      appId={process.env.REACT_APP_MORALIS_APP_ID}
    >
      <NotificationProvider>
        <Dashboard />
      </NotificationProvider>
    </MoralisProvider>
  );
}

export default App;

Step 3 - Creating the ConnectButton Component

In this step, we're going to create the connect wallet component, so that we can log in to the dashboard with our wallet (e.g. Metamask).

In your src folder:

  • Create a new components folder
  • In the components folder, create a new ConnectWallet.jsx file with the following code:
import React from "react";
import { ConnectButton, Hero } from "web3uikit";

export const ConnectWallet = () => {
  return (
    <section className='not-connected'>
      <Hero
        backgroundURL='https://moralis.io/wp-content/uploads/2021/06/blue-blob-background-2.svg'
        title='My Web3 Dashboard ๐Ÿš€'
        height='70vh'
      >
        <ConnectButton signingMessage='Connect wallet' />
      </Hero>
    </section>
  );
};

In the code above, we're rendering the <Hero /> and the <ConnectButton /> component.

This is the output of the <ConnectWallet /> component we used above:

building a web3UI login interface for users to connect with their wallet using Metamask

Now, the user is able to connect with any of their digital wallets: User prompted to connect their wallet

The wallet modal is from the <ConnectButton /> component.

Step 4 - Building the dApp Dashboard

In this step, we'll build the dashboard components that'll display the following:

The balance of the connected user on the Mainnet, Kovan, Rinkeby, Goerli, and Ropsten Testnets

A toggle card that displays the wallet address of a connected user

A todo list to add and delete tasks

The NFTs owned by the connected user

From your components folder:

  • Create a new Dashboard.jsx file with the code below:
import Moralis from "moralis";
import React, { useEffect } from "react";
import { useMoralis, useMoralisWeb3Api } from "react-moralis";
import {
  BannerStrip,
  NFTBalance,
  ConnectButton,
  useNotification,
  Widget,
  Todo,
  Credentials,
  Typography,
} from "web3uikit";
import { ConnectWallet } from "./ConnectWallet";

export const Dashboard = () => {
  const dispatch = useNotification();
  const Web3Api = useMoralisWeb3Api();
  const { isAuthenticated, user } = useMoralis();
  // Current user's wallet address
  const userAddress = user?.get("ethAddress");

  // Token balance of the current user
  const [mainnetBalance, setMainnetBalance] = React.useState("0");
  const [kovanBalance, setKovanBalance] = React.useState("0");
  const [rinkebyBalance, setRinkebyBalance] = React.useState("0");
  const [goerliBalance, setGoerliBalance] = React.useState("0");
  const [ropstenBalance, setRopstenBalance] = React.useState("0");

  // Notification handler
  const handleNewNotification = ({ type, title, message, position }) => {
    dispatch({
      type: type || "info",
      message: message || "",
      title: title || "New Notification",
      position: position || "topR",
    });
  };

  // Get the balance of the current user
  const fetchTokenBalances = async (chain) => {
    const options = { chain, address: userAddress };
    const result = await Web3Api.account.getNativeBalance(options);
    return result.balance;
  };

  // Fetch all token balances of the current user
  const fetchBalances = async () => {
    const balances = await Promise.all([
      fetchTokenBalances("mainnet"),
      fetchTokenBalances("kovan"),
      fetchTokenBalances("rinkeby"),
      fetchTokenBalances("goerli"),
      fetchTokenBalances("ropsten"),
    ]);

    // Balance of the current user on each chain
    const mainnetBalance = balances[0];
    const kovanBalance = balances[1];
    const rinkebyBalance = balances[2];
    const goerliBalance = balances[3];
    const ropstenBalance = balances[4];

    // Convert the balance from Wei to Ether
    const mainnetBalanceEther = Moralis.Units.FromWei(mainnetBalance);
    const kovanBalanceEther = Moralis.Units.FromWei(kovanBalance);
    const rinkebyBalanceEther = Moralis.Units.FromWei(rinkebyBalance);
    const goerliBalanceEther = Moralis.Units.FromWei(goerliBalance);
    const ropstenBalanceEther = Moralis.Units.FromWei(ropstenBalance);

    // Set the ETH balance of the current user
    setMainnetBalance(mainnetBalanceEther);
    setKovanBalance(kovanBalanceEther);
    setRinkebyBalance(rinkebyBalanceEther);
    setGoerliBalance(goerliBalanceEther);
    setRopstenBalance(ropstenBalanceEther);
  };

  useEffect(() => {
    if (isAuthenticated) {
      // Notification object
      const notificationData = {
        types: "info",
        title: "Wallet Connected ๐Ÿค",
        position: "bottomR",
      };

      // Show notification
      handleNewNotification(notificationData);

      // Fetches all token balances of the current user
      fetchBalances();
    }
  }, [isAuthenticated]);

  return (
    <React.Fragment>
      <header>
        {/* Dapp Header Banner */}
        <BannerStrip
          text={
            isAuthenticated
              ? "Welcome back ๐Ÿ‘‹"
              : "You are not connected to the dApp. Please connect to the dApp to see your NFT balance."
          }
          height='40px'
          className='dapp-header-banner'
        />

        {/* Dapp Authentication */}
        <section className='container topnav'>
          <Typography variant='h2'>My Web3 Dashboard</Typography>
          <ConnectButton signingMessage='Connect wallet' />
        </section>
      </header>
      <main>
        {isAuthenticated ? (
          <section className='container'>
            {/* Dapp Balance Widget */}
            <section className='wallet-balance-widget'>
              <Widget
                title='MAINNNET'
                info={`${mainnetBalance.slice(0, 10)} ETH`}
              />
              <Widget
                title='RINKEBY'
                info={`${rinkebyBalance.slice(0, 10)} ETH`}
              />
              <Widget title='KOVAN' info={`${kovanBalance.slice(0, 10)} ETH`} />
              <Widget
                title='GOERLI'
                info={`${goerliBalance.slice(0, 10)} ETH`}
              />
              <Widget
                title='ROPSTEN'
                info={`${ropstenBalance.slice(0, 10)} ETH`}
              />
            </section>

            {/* Wallet Address  */}
            <section className='my-secret-credential'>
              <Credentials
                icon='info'
                text={userAddress}
                title='Wallet Address:'
              />
            </section>

            {/* Dapp Todo */}
            <section className='todo-container'>
              <Todo
                label='Enter IP'
                onChange={function noRefCheck() {}}
                todos={[]}
              />
            </section>

            {/* Dapp NFT Owned by user */}
            <section className='my-nfts-section'>
              <NFTBalance address={userAddress} chain='rinkeby' />
            </section>
          </section>
        ) : (
          // Dapp Connect Wallet
          <ConnectWallet />
        )}
      </main>

      <footer className='container'>
        Powered by <a href='https://moralis.io'>Moralis Web3UIKit</a>
      </footer>
    </React.Fragment>
  );
};

In the code above:

  • The dashboard contents will only be accessible if a wallet is connected.

We check whether or not a wallet is connected with the Moralis isAuthenticated state.

  • We're fetching the balance of the connected user from all the chains using promise.all() and converting it from wei to ether.

  • We're also displaying all the userโ€™s NFTs in the rinkeby network.

Replace your index.css content with the following lines of code:

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

body {
  font-family: Arial;
}

.container {
  padding: 20px;
}

.not-connected > * > h1 {
  z-index: 0 !important;
}

.topnav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 50px;
  margin-bottom: 20px;
}

.wallet-balance-widget {
  display: flex;
  gap: 20px;
  margin: 30px 0;
}

.todo-container {
  margin: 30px 0;
  width: 100%;
}

.todo-container section {
  padding: 0;
}

/* MY NFTS SECTION */
.my-nfts-section > section {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  margin: 30px 0;
}

footer {
  text-align: center;
  margin-top: 50px;
}

When a wallet is connected, our dApp dashboard should look something like this:

building a Web3 dApp dashboard to display connected user's balance on both Mainnet and Testnet using Web3UI Kit and React

You Made It ๐Ÿ‘

Our dApp dashboard is code ready; you can go ahead and connect your wallet to access the dashboard or follow the How it Works.

You can find the complete React source code for our tutorial here.

Conclusion

This article demonstrates how to install and build your dApp frontend with the Moralis Web3UIKit.

The Web3UIKit is an open source frontend library for building Web3 projects interface and it's maintained by Moralis. You can contribute to the Web3UI Kit from their official repository here.

Where Do You Go Next?

Now that you know how to build an NFT minting smart contract and how to interact with it from a React application:

  • Learn How to Build a Web3 Login With Web3.js Library here.

  • Learn How to Build Your Own NFT Explorer With Moralis React SDK here.

  • Learn How to Build and Deploy an NFT Minting dApp With Solidity and React here.


This article is a part of the Hashnode Web3 blog, where a team of curated writers are bringing out new resources to help you discover the universe of web3. Check us out for more on NFTs, DAOs, blockchains, and the decentralized future.

ย