How to build simple Web3 Application with React and Vite (Part 1)
Tags: react, vite, webdev, web3
Published: 2022-10-18 16:30:33

On this part, you'll learn how to connect to blockchain network using [wagmi](https://wagmi.sh/)

## Prerequisites ##
- NodeJS installed
- MetaMask extension installed in your browser

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

npm:
```typescript
$ npm create vite simple-dapp --template react-ts
```

yarn:
```typescript
$ yarn create vite simple-dapp --template react-ts
```

pnpm:
```typescript
$ pnpm create vite simple-dapp --template react-ts
```



**Next, we will install [wagmi](https://wagmi.sh/) - a collection of React Hooks containing everything you need to start working with Ethereum and [ethers.js](https://docs.ethers.io/v5/)**

```typescript
$ pnpm add wagmi ethers
```

**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.

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

const { chains, provider, webSocketProvider } = configureChains(defaultChains, [publicProvider()])
```
`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](https://wagmi.sh/docs/providers/alchemy) or [infuraProvider](https://wagmi.sh/docs/providers/infura).

###2. Create a wagmi client instance
Next, create a wagmi Client instance using `createClient`, and pass the result from `configureChains` to it.

```typescript
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
})
```
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.

```typescript
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
  <React.StrictMode>
    <WagmiConfig client={client}>
      <App />
    </WagmiConfig>
  </React.StrictMode>
)
```

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

`WalletConnect.tsx`

```typescript
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>
}
```

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`

```typescript
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>
  )
}
```

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

![Project layout when wallet unconnected](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ey5b6ol7l5b8ymqpoa1w.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f9s9uannuotzd7urse8b.png)

![Metamask confirm connect step](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jkqdkkkhpoyre12gxkdy.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/feq5nxx0nhqc096wot81.png)

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.**