@thirdweb-dev/react
TypeScript icon, indicating that this package has built-in type declarations

4.6.7 • Public • Published



thirdweb React SDK

npm version Build Status Join our Discord!

Ultimate collection of React hooks for your web3 apps



Installation

The easiest way to get started with the React SDK is to use the CLI:

npx thirdweb create --app

Alternatively, you can install the SDK into your existing project using npm or yarn:

npm install @thirdweb-dev/react @thirdweb-dev/sdk ethers@5
yarn add @thirdweb-dev/react @thirdweb-dev/sdk ethers@5

Getting Started

Our SDK uses a Provider Pattern; meaning any component within the ThirdwebProvider will have access to the SDK. If you use the CLI to initialize your project, this is already set up for you.

Let's take a look at a typical setup:


Configure the ThirdwebProvider

Specify the network your smart contracts are deployed to in the desiredChainId prop and wrap your application like so:

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

const App = () => {
  return (
    <ThirdwebProvider desiredChainId={ChainId.Mainnet}>
      <YourApp />
    </ThirdwebProvider>
  );
};

Below are examples of where to set this up in your application:

Create React AppNext.jsVite


Connect to a User's Wallet

Now the provider is set up, we can use all of the hooks and UI components available in the SDK, such as the ConnectWallet component.

Once the user has connected their wallet, all the calls we make to interact with contracts using the SDK will be on behalf of the user.

import { ConnectWallet, useAddress } from "@thirdweb-dev/react";

export const YourApp = () => {
  const address = useAddress();
  return (
    <div>
      <ConnectWallet />
    </div>
  );
};

The ConnectWallet component handles everything for us, including switching networks, accounts, displaying balances and more.

We can then get the connected address using the useAddress hook anywhere in the app.


Interact With Contracts

Connect to your smart contract using the useContract hook like so:

import { useContract } from "@thirdweb-dev/react";

export default function Home() {
  const { contract } = useContract("<CONTRACT_ADDRESS>");

  // Now you can use the contract in the rest of the component!
}

You can then use useContractRead and useContractWrite to read data and write transactions to the contract.

You pass the contract object returned from useContract to these hooks as the first parameter and the name of the function (or view/mapping, etc.) on your smart contract as the second parameter. If your function requires parameters, you can pass them as additional arguments.

For example, we can read the name of our contract like so:

import {
  useContract,
  useContractRead,
  useContractWrite,
} from "@thirdweb-dev/react";

export default function Home() {
  const { contract } = useContract("<CONTRACT_ADDRESS>");
  const { data: name, isLoading: loadingName } = useContractRead(
    contract,
    "name", // The name of the view/mapping/variable on your contract
  );
  const { mutate: setName, isLoading: settingName } = useContractWrite(
    contract,
    "setName", // The name of the function on your contract
  );
}

Using Extensions

Each extension you implement in your smart contract unlocks new functionality in the SDK.

These hooks make it easy to interact with your smart contracts by implementing the complex logic for you under the hood.

For example, if your smart contract implements ERC721Supply, you unlock the ability to view all NFTs on that contract using the SDK; which fetches all of your NFT metadata and the current owner of each NFT in parallel. In the React SDK, that is available using useNFTs:

import { useContract, useNFTs } from "@thirdweb-dev/react";

export default function Home() {
  const { contract } = useContract("<CONTRACT_ADDRESS>");
  const { data: nfts, isLoading: isReadingNfts } = useNFTs(contract);
}

If we want to mint an NFT and our contract implements ERC721Mintable, we can use the useMintNFT hook to mint an NFT from the connected wallet; handling all of the logic of uploading and pinning the metadata to IPFS for us behind the scenes.

import { useContract, useNFTs, useMintNFT } from "@thirdweb-dev/react";

export default function Home() {
  const { contract } = useContract("<CONTRACT_ADDRESS>");
  const { data: nfts, isLoading: isReadingNfts } = useNFTs(contract);
  const { mutate: mintNFT, isLoading: isMintingNFT } = useMintNFT(contract);
}

UI Components

The SDK provides many UI components to help you build your application.

For example, we can render each of the NFTs using the NFT Media Renderer component, making use of the loading state from useNFTs:

import { useContract, useNFTs, ThirdwebNftMedia } from "@thirdweb-dev/react";

export default function Home() {
  const { contract } = useContract("<CONTRACT_ADDRESS>");
  const { data: nfts, isLoading: isReadingNfts } = useNFTs(contract);

  return (
    <div>
      <h2>My NFTs</h2>
      {isReadingNfts ? (
        <p>Loading...</p>
      ) : (
        <div>
          {nfts.map((nft) => (
            <ThirdwebNftMedia
              key={nft.metadata.id}
              metadata={nft.metadata}
              height={200}
            />
          ))}
        </div>
      )}
    </div>
  );
}

The Web3Button component ensures the user has connected their wallet and is currently configured to the same network as your smart contract before calling the function. It also has access to the contract directly, allowing you to perform any action on your smart contract when the button is clicked.

For example, we can mint an NFT like so:

import {
  useContract,
  useNFTs,
  ThirdwebNftMedia,
  Web3Button,
} from "@thirdweb-dev/react";

const contractAddress = "<CONTRACT_ADDRESS>";
export default function Home() {
  const { contract } = useContract(contractAddress);
  const { data: nfts, isLoading: isReadingNfts } = useNFTs(contract);

  return (
    <div>
      {/* ... Existing Display Logic here ... */}

      <Web3Button
        contractAddress={contractAddress}
        action={(contract) =>
          contract.erc721.mint({
            name: "Hello world!",
            image:
              // You can use a file or URL here!
              "ipfs://QmZbovNXznTHpYn2oqgCFQYP4ZCpKDquenv5rFCX8irseo/0.png",
          })
        }
      >
        Mint NFT
      </Web3Button>
    </div>
  );
}

Advanced Configuration

The ThirdwebProvider offers a number of configuration options to control the behavior of the React and Typescript SDK.

These are all the configuration options of the <ThirdwebProvider />. We provide defaults for all of these, but you customize them to suit your needs.

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

const KitchenSinkExample = () => {
  return (
    <ThirdwebProvider
      desiredChainId={ChainId.Mainnet}
      chainRpc={{ [ChainId.Mainnet]: "https://mainnet.infura.io/v3" }}
      dAppMeta={{
        name: "Example App",
        description: "This is an example app",
        isDarkMode: false,
        logoUrl: "https://example.com/logo.png",
        url: "https://example.com",
      }}
      storageInterface={new IpfsStorage("https://your.ipfs.host.com")}
      supportedChains={[ChainId.Mainnet]}
      walletConnectors={[
        "walletConnect",
        { name: "injected", options: { shimDisconnect: false } },
        {
          name: "walletLink",
          options: {
            appName: "Example App",
          },
        },
        {
          name: "magic",
          options: {
            apiKey: "your-magic-api-key",
            rpcUrls: {
              [ChainId.Mainnet]: "https://mainnet.infura.io/v3",
            },
          },
        },
      ]}
      sdkOptions={{
        gasSettings: { maxPriceInGwei: 500, speed: "fast" },
        readonlySettings: {
          chainId: ChainId.Mainnet,
          rpcUrl: "https://mainnet.infura.io/v3",
        },
        gasless: {
          openzeppelin: {
            relayerUrl: "your-relayer-url",
          },
        },
      }}
    >
      <YourApp />
    </ThirdwebProvider>
  );
};

Available hooks

Main hooks

Hook Description
useSDK Access the instance of the thirdweb SDK created by the ThirdwebProvider.
useContract Use this resolve a contract address to a smart contract instance.
useContractWrite Use this to get data from a contract read-function call.
useContractRead Use this to get a function to make a write call to your contract.
useContractEvents Use this to get the contract metadata for a (built-in or custom) contract.
useContractMetadata Use this to get the contract metadata for a (built-in or custom) contract.

Wallet connection

Hook Description
useAddress Hook for accessing the address of the connected wallet.
useMetamask Hook for connecting to a Metamask wallet.
useWalletConnect Hook for connecting to a mobile wallet with Wallet Connect.
useCoinbaseWallet Hook for connecting to a Coinbase wallet.
useMagic Hook for connecting to an email wallet using magic link.
useGnosis Hook for connecting to a Gnosis Safe.
useDisconnect Hook for disconnecting the currently connected wallet.

Network connection

Hook Description
useChainId Hook for accessing the chain ID of the network the current wallet is connected to
useNetwork Hook for getting metadata about the network the current wallet is connected to and switching networks.
useNetworkMismatch Hook for checking whether the connected wallet is on the correct network specified by the desiredChainId passed to the .

NFT

Hook Description
useNFT Use this to get an individual NFT token of your NFTContract.
useNFTs Use this to get a list of NFT tokens of your NFTContract.
useTotalCirculatingSupply Use this to get a the total (minted) supply of your NFTContract.
useOwnedNFTs Use this to get a the owned NFTs for a specific Erc721OrErc1155 and wallet address.
useNFTBalance Use this to get a the total balance of a NFTContract and wallet address.
useTotalCount Use this to get the total count of NFT tokens of your NFTContract.
useMintNFT Use this to mint a new NFT on your Erc721OrErc1155.
useMintNFTSupply Use this mint extra supply on your Erc1155.
useTransferNFT Use this to transfer tokens on your NFTContract.
useAirdropNFT Use this to airdrop tokens on your Erc1155.
useBurnNFT Use this to burn an NFT on your Erc721OrErc1155.

Token

Hook Description
useTokenSupply Use this to get a the total supply of your contract.
useTokenBalance Use this to get the balance of your contract for a given address.
useTokenDecimals Use this to get the decimals of your contract for a given address.
useMintToken Use this to mint new tokens on your contract.
useClaimToken Use this to claim tokens from your contract.
useTransferToken Use this to transfer tokens on your contract.
useTransferBatchToken Use this to transfer batch tokens on your contract.
useBurnToken Use this to burn tokens on your contract.

Marketplace

Hook Description
useListing Use this to get a specific listing from the marketplace.
useListings Use this to get a list all listings from your marketplace contract.
useListingsCount Use this to get a count of all listings on your marketplace contract.
useActiveListings Use this to get a list active listings from your marketplace contract.
useWinningBid Use this to get a the winning bid for an auction listing from your marketplace contract.
useAuctionWinner Use this to get the winner of an auction listing from your marketplace contract.
useBidBuffer Use this to get the buffer in basis points between offers from your marketplace contract.
useCreateDirectListing Use this to create a new Direct Listing on your marketplace contract.
useCreateAuctionListing Use this to create a new Auction Listing on your marketplace contract.
useCancelListing Use this to cancel a listing on your marketplace contract.
useMakeBid Use this to place a bid on an auction listing from your marketplace contract.
useBuyNow Use this to buy out an auction listing from your marketplace contract.
useBuyDirectListing Use this to buy from a direct listing in your marketplace v3 contract.

Permissions Controls

Hook Description
useAllRoleMembers Use this to get the roles of all members.
useRoleMembers Use this to get the members of a role.
useIsAddressRole Use this to check if a WalletAddress is a member of a role.
useSetAllRoleMembers Use this to OVERWRITE the list of addresses that are members of specific roles.
useGrantRole Use this to grant a WalletAddress a specific role.
useRevokeRole Use this to revoke a WalletAddress a specific role.

Drop

Hook Description
useUnclaimedNFTs Use this to get a list of unclaimed NFT tokens of your ERC721 Drop contract.
useClaimedNFTs Use this to get a list of claimed (minted) NFT tokens of your ERC721 Drop contract..
useUnclaimedNFTSupply Use this to get the total unclaimed NFT supply of your ERC721 Drop contract.
useClaimedNFTSupply Use this to get the total claimed (minted) NFT supply of your ERC721 Drop contract.
useBatchesToReveal Use this to get a list of batches that are ready to be revealed.
useClaimNFT Use this to claim a NFT on your DropContract
useLazyMint Use this to lazy mint a batch of NFTs on your DropContract.
useDelayedRevealLazyMint Use this to lazy mint a batch of delayed reveal NFTs on your DropContract.
useRevealLazyMint Use this to reveal a batch of delayed reveal NFTs on your RevealableContract.

Claim Conditions

Hook Description
useActiveClaimCondition Use this to get the active claim condition for ERC20, ERC721 or ERC1155 based contracts.
useClaimConditions Use this to get all claim conditions for ERC20, ERC721 or ERC1155 based contracts.
useClaimIneligibilityReasons Use this to check for reasons that prevent claiming for either ERC20, ERC721 or ERC1155 based contracts.
useSetClaimConditions Use this to set claim conditions on your DropContract.
useResetClaimConditions Use this to reset claim conditions on your DropContract.

Readme

Keywords

none

Package Sidebar

Install

npm i @thirdweb-dev/react

Weekly Downloads

33,177

Version

4.6.7

License

Apache-2.0

Unpacked Size

3.87 MB

Total Files

524

Last publish

Collaborators

  • furqantw
  • yash90
  • krishang
  • jakeloo
  • joaquim-verges
  • jnsdls