Skip to main content

Add a connect wallet button to your website

· 2 min read
Nacho Iacovino

Learn how to easily add a connect wallet button to your web application using the React SDK.

Introduction

Setting up web3 on your website and letting your users connect their wallets is essential for any web3 web app.

thirdweb's SDK allows you to connect to all of the most popular wallets:

tip

Wallet connection comes pre-configured when you create new projects using create-tw-app:

npx thirdweb create

Get Started

To get started with thirdweb, you can run the following to install our packages into an existing React project:

# Run this to install with npm
npm install @thirdweb-dev/react @thirdweb-dev/sdk ethers

# Or run this to install with yarn
yarn add @thirdweb-dev/react @thirdweb-dev/sdk ethers

Once you've installed the necessary packages, set up the ThirdwebProvider to wrap the rest of your application:

import { ThirdwebProvider, ChainId } from "@thirdweb-dev/react";

function MyApp({ Component, pageProps }) {
const desiredChainId = ChainId.Mumbai;

/**
* Make sure that your app is wrapped with these contexts.
* If you're using React, you'll have to replace the Component setup with {children}
*/
return (
<ThirdwebProvider desiredChainId={desiredChainId}>
<Component {...pageProps} />
</ThirdwebProvider>
);
}

export default MyApp;

Connect Wallet

Now you're ready to use one of our Wallet Connection hooks to connect users' wallets to your site.

import {
useMetamask,
useWalletConnect,
useCoinbaseWallet,
useNetwork,
useAddress,
useDisconnect,
} from "@thirdweb-dev/react";
export const ConnectWallet = () => {
const connectWithCoinbaseWallet = useCoinbaseWallet();
const connectWithMetamask = useMetamask();
const connectWithWalletConnect = useWalletConnect();
const disconnectWallet = useDisconnect();
const address = useAddress();
const network = useNetwork();
// If a wallet is connected, show address, chainId and disconnect button
if (address) {
return (
<div>
Address: {address}
<br />
Chain ID: {network[0].data.chain && network[0].data.chain.id}
<br />
<button onClick={disconnectWallet}>Disconnect</button>
</div>
);
}
// If no wallet is connected, show connect wallet options
return (
<div>
<button onClick={() => connectWithCoinbaseWallet()}>
Connect Coinbase Wallet
</button>
<button onClick={() => connectWithMetamask()}>Connect MetaMask</button>
<button onClick={() => connectWithWalletConnect()}>
Connect WalletConnect
</button>
</div>
);
};

Then, we need to import this component on our index.tsx file:

pages/index.tsx
import type { NextPage } from "next";
import { ConnectWallet } from "../components/ConnectWallet";
const Home: NextPage = () => {
return (
<div>
<ConnectWallet />
</div>
);
};
export default Home;