DEV Community

Cover image for How to build simple Web3 Application with React and Vite (Part 1)
Tri Hoang
Tri Hoang

Posted on

How to build simple Web3 Application with React and Vite (Part 1)

On this part, you'll learn how to connect to blockchain network using wagmi

Prerequisites

  • NodeJS installed
  • MetaMask extension installed in your browser

Getting started

To get started, we'll create a new React application using vite:

npm:

$ npm create vite simple-dapp --template react-ts
Enter fullscreen mode Exit fullscreen mode

yarn:

$ yarn create vite simple-dapp --template react-ts
Enter fullscreen mode Exit fullscreen mode

pnpm:

$ pnpm create vite simple-dapp --template react-ts
Enter fullscreen mode Exit fullscreen mode

Next, we will install wagmi - a collection of React Hooks containing everything you need to start working with Ethereum and ethers.js

$ pnpm add wagmi ethers
Enter fullscreen mode Exit fullscreen mode

Then, we will update our main.tsx(or index.tsx) in order to create our wagmi client to connect with blockchain network."

1. Configure chains

First, configure your desired chains to be used by wagmi, and the providers you want to use.

import { WagmiConfig, createClient, configureChains, defaultChains } from 'wagmi'
import { publicProvider } from 'wagmi/providers/public'

const { chains, provider, webSocketProvider } = configureChains(defaultChains, [publicProvider()])
Enter fullscreen mode Exit fullscreen mode

defaultChains will be the list of popular blockchain networks (Ethereum mainnet, testnet, polygon, optimism, ...)

Note: It is not recommended to only pass publicProvider to configureChains as you will probably face rate-limiting on the public provider endpoints. It is recommended to use alchemyProvider or infuraProvider.

2. Create a wagmi client instance

Next, create a wagmi Client instance using createClient, and pass the result from configureChains to it.

import { WagmiConfig, createClient, configureChains, defaultChains } from 'wagmi'
import { publicProvider } from 'wagmi/providers/public'
import { MetaMaskConnector } from 'wagmi/connectors/metaMask'

const { chains, provider, webSocketProvider } = configureChains(defaultChains, [publicProvider()])
const client = createClient({
  autoConnect: true,
  connectors: [new MetaMaskConnector({ chains })],
  provider,
  webSocketProvider
})
Enter fullscreen mode Exit fullscreen mode

We will use Metamask to connect our wallet to blockchain network

3. Wrap app with WagmiConfig

Finally, wrap your app with the WagmiConfig component, passing client to it.

ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
  <React.StrictMode>
    <WagmiConfig client={client}>
      <App />
    </WagmiConfig>
  </React.StrictMode>
)
Enter fullscreen mode Exit fullscreen mode

Now we are good to go, let's create WalletConnect component to connect to any blockchain networks

WalletConnect.tsx

import { chain as Chain, useAccount, useConnect, useDisconnect } from 'wagmi'

export interface WalletConnectProps {}

export const WalletConnect = ({}: WalletConnectProps) => {
  const { isConnected, address } = useAccount()
  const { connect, connectors } = useConnect()
  const { disconnect } = useDisconnect()

  const handleConnect = () => {
    connect({
      connector: connectors[0], // metamask
      chainId: Chain.goerli.id // chainId = 5, goerli is Ethereum testnet
    })
  }

  const handleDisconnect = () => {
    disconnect()
  }

  if (isConnected) {
    return (
      <div>
        <p>Address: {address}</p>
        <button onClick={handleDisconnect}>Disconnect Wallet</button>
      </div>
    )
  }

  return <button onClick={handleConnect}>Connect Wallet</button>
}
Enter fullscreen mode Exit fullscreen mode

In the connect function, we will pass a config that include connector we want to use (in this case it is metamask) and the network that we want to connect (in this case it is goerli testnet)

We now good to go, let's import WalletConnect component to our App.tsx and run our project

App.tsx

function App() {
  return (
    <div className='App'>
      <div>
        <a href='https://vitejs.dev' target='_blank'>
          <img src='/vite.svg' className='logo' alt='Vite logo' />
        </a>
        <a href='https://reactjs.org' target='_blank'>
          <img src={reactLogo} className='logo react' alt='React logo' />
        </a>
      </div>
      <h1>Simple dApp</h1>
      <WalletConnect />
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

This is our app when we haven't connect to any network

Project layout when wallet unconnected

Now let's click to the connect button to connect to Goerli testnet.
After clicking, metamask will prompt a popup to select account (or confirm whether you want to connect your wallet to this app if you had only 1 account)

Metamask select account step

Metamask confirm connect step

After confirm on your metamask, you will notice that your wallet has been connected to our app

and yayyy, your address will be shown on our app

Project layout when wallect connected

You are able to click to disconnect button to disconnect your wallet to our app as well.

On Part 2 of this tutorial, you'll learn how to switch from current network to others network, as well as how to read/write data within an existing smart contract.

Top comments (0)