React Component Library

The Cart.fun React Component Library provides ready-made UI components for building decentralized e-commerce applications on the Solana blockchain using the Cart.fun protocol.

Installation

Step 1: Install the Component Library

npm install @cartdotfun/react

Step 2: Install Peer Dependencies

npm install @solana/web3.js @solana/wallet-adapter-react @cartdotfun/sdk react react-dom

Getting Started

Basic Setup

First, set up your React application with the Cart.fun provider:

import React from 'react'
import { createRoot } from 'react-dom/client'
import { CartProvider } from '@cartdotfun/react'
import { Connection } from '@solana/web3.js'
import {
  WalletProvider,
  ConnectionProvider,
} from '@solana/wallet-adapter-react'
import App from './App'

// Configure your Solana connection and wallet adapters
const connection = new Connection('https://api.devnet.solana.com')
const walletAdapters = [] // Add your preferred wallet adapters

const root = createRoot(document.getElementById('root'))
root.render(
  <ConnectionProvider endpoint="https://api.devnet.solana.com">
    <WalletProvider wallets={walletAdapters} autoConnect>
      <CartProvider network="devnet">
        <App />
      </CartProvider>
    </WalletProvider>
  </ConnectionProvider>,
)

Using Components

Now you can use Cart.fun components in your app:

import React from 'react'
import {
  ProductCard,
  ConnectWalletButton,
  MarketplaceView,
} from '@cartdotfun/react'

function App() {
  return (
    <div className="app">
      <header>
        <h1>My Decentralized Store</h1>
        <ConnectWalletButton />
      </header>

      <main>
        <MarketplaceView marketplaceId="my-marketplace-id" />
      </main>
    </div>
  )
}

export default App

Core Components

The library provides several foundational components that serve as building blocks for your application.

CartProvider

Provides global Cart.fun context to your application:

<CartProvider
  network="devnet" // 'devnet', 'testnet', or 'mainnet-beta'
  rpcUrl="https://custom-rpc.example.com" // Optional custom RPC URL
  autoConnect={true} // Automatically connect wallet if available
>
  {children}
</CartProvider>
  • Name
    network
    Type
    string
    Description

    Solana network to connect to ('devnet', 'testnet', or 'mainnet-beta')

  • Name
    rpcUrl
    Type
    string
    Description

    Optional custom RPC URL

  • Name
    autoConnect
    Type
    boolean
    Description

    Whether to automatically connect wallet

  • Name
    onError
    Type
    function
    Description

    Error handler function

ConnectWalletButton

Button component for connecting Solana wallets:

<ConnectWalletButton
  label="Connect Wallet"
  labelConnected="My Wallet"
  appearance="primary" // 'primary', 'secondary', 'outline'
/>
  • Name
    label
    Type
    string
    Description

    Button text when disconnected

  • Name
    labelConnected
    Type
    string
    Description

    Button text when connected

  • Name
    appearance
    Type
    string
    Description

    Button style variant

  • Name
    size
    Type
    string
    Description

    Button size ('small', 'medium', 'large')

TransactionButton

Button that handles Solana transaction submission and state:

<TransactionButton
  label="Purchase"
  loadingLabel="Processing..."
  successLabel="Purchased!"
  errorLabel="Failed"
  onBeforeTransaction={() => {
    // Pre-transaction validation or preparation
    return true // Return false to cancel transaction
  }}
  onTransaction={async () => {
    // Return transaction or transaction signature
    return await myPurchaseFunction()
  }}
  onSuccess={(signature) => {
    console.log('Transaction succeeded:', signature)
  }}
  onError={(error) => {
    console.error('Transaction failed:', error)
  }}
/>

Product Components

ProductCard

Card component for displaying product information:

<ProductCard
  product={productData}
  showPrice={true}
  showVendor={true}
  onAddToCart={() => {
    /* ... */
  }}
  onProductClick={() => {
    /* ... */
  }}
/>
  • Name
    product
    Type
    object
    Description

    Product data object

  • Name
    showPrice
    Type
    boolean
    Description

    Whether to display price

  • Name
    showVendor
    Type
    boolean
    Description

    Whether to display vendor info

  • Name
    orientation
    Type
    string
    Description

    'vertical' or 'horizontal' layout

  • Name
    size
    Type
    string
    Description

    Card size ('small', 'medium', 'large')

ProductGrid

Grid layout for displaying multiple products:

<ProductGrid
  products={productsArray}
  columns={3}
  gap="1rem"
  onProductClick={(product) => {
    /* ... */
  }}
/>

ProductDetail

Detailed product view with purchase options:

<ProductDetail
  productId="product-id-here"
  showRelatedProducts={true}
  onPurchase={(product) => {
    /* ... */
  }}
/>

PurchaseButton

Button for purchasing a product:

<PurchaseButton
  productId="product-id-here"
  quantity={1}
  onSuccess={(signature) => {
    /* ... */
  }}
  disabled={false}
  size="medium"
/>

Vendor Components

VendorCard

Card component for displaying vendor information:

<VendorCard
  vendor={vendorData}
  showStats={true}
  orientation="vertical"
  size="medium"
/>

VendorDashboard

Complete dashboard for vendors to manage their store:

<VendorDashboard
  vendorId="vendor-id-here"
  tabs={['products', 'orders', 'analytics']}
  initialTab="products"
/>

ProductForm

Form for vendors to create or edit products:

<ProductForm
  initialData={existingProduct} // Optional, for editing
  onSubmit={(productData) => {
    /* ... */
  }}
  marketplaceId="marketplace-id-here"
/>

Marketplace Components

MarketplaceView

Complete marketplace view with products, categories, and search:

<MarketplaceView
  marketplaceId="marketplace-id-here"
  layout="grid" // 'grid' or 'list'
  showSearch={true}
  showCategories={true}
  productsPerPage={12}
/>

CategoryList

Component to display and navigate marketplace categories:

<CategoryList
  marketplaceId="marketplace-id-here"
  orientation="horizontal" // 'horizontal' or 'vertical'
  onCategorySelect={(category) => {
    /* ... */
  }}
/>

SearchBar

Search component for marketplaces:

<SearchBar
  marketplaceId="marketplace-id-here"
  placeholder="Search products..."
  onSearch={(query) => {
    /* ... */
  }}
  showFilters={true}
/>

Hooks

The library provides custom React hooks for interacting with the Cart.fun protocol.

useCart

Hook for managing shopping cart functionality:

const { cart, addToCart, removeFromCart, updateQuantity, clearCart, checkout } =
  useCart()

useProducts

Hook for fetching and managing products:

const {
  products,
  loading,
  error,
  fetchProducts,
  fetchProductById,
  createProduct,
  updateProduct,
} = useProducts(marketplaceId)

useVendor

Hook for accessing vendor functionality:

const {
  vendor,
  loading,
  error,
  stats,
  products,
  registerAsVendor,
  updateVendorProfile,
} = useVendor(vendorId)

useMarketplace

Hook for marketplace interaction:

const { marketplace, loading, error, categories, vendors, featuredProducts } =
  useMarketplace(marketplaceId)

useTransaction

Hook for advanced transaction management:

const {
  submit,
  status, // 'idle', 'preparing', 'processing', 'confirming', 'success', 'error'
  signature,
  error,
  confirmations,
} = useTransaction()

// Usage example
const handleClick = async () => {
  await submit(() => myTransactionFunction())
}

Theming

The component library supports theme customization to match your brand identity.

ThemeProvider

Customize the appearance of all components:

import { ThemeProvider } from '@cartdotfun/react'

const myTheme = {
  colors: {
    primary: '#0088CC',
    secondary: '#22CCAA',
    accent: '#FF5500',
    background: '#FFFFFF',
    text: '#333333',
    error: '#FF0000',
    success: '#00CC00',
  },
  fonts: {
    body: '"Inter", system-ui, sans-serif',
    heading: '"Montserrat", system-ui, sans-serif',
  },
  borderRadius: '8px',
  shadows: {
    small: '0 2px 4px rgba(0,0,0,0.1)',
    medium: '0 4px 8px rgba(0,0,0,0.1)',
    large: '0 8px 16px rgba(0,0,0,0.1)',
  },
}

function App() {
  return (
    <ThemeProvider theme={myTheme}>
      <YourApplication />
    </ThemeProvider>
  )
}

Component-Specific Styling

Many components accept style props for one-off customization:

<ProductCard
  product={productData}
  style={{
    backgroundColor: '#f5f5f5',
    maxWidth: '300px',
  }}
  imageStyle={{
    borderRadius: '50%',
  }}
/>

Examples

Complete Marketplace Application

import React from 'react'
import {
  CartProvider,
  ConnectWalletButton,
  MarketplaceView,
  SearchBar,
  CategoryList,
  ShoppingCart,
} from '@cartdotfun/react'

function MarketplaceApp() {
  return (
    <CartProvider network="devnet">
      <div className="app">
        <header>
          <h1>Solana Marketplace</h1>
          <div className="header-actions">
            <SearchBar marketplaceId="my-marketplace" />
            <ShoppingCart />
            <ConnectWalletButton />
          </div>
        </header>

        <nav>
          <CategoryList
            marketplaceId="my-marketplace"
            orientation="horizontal"
          />
        </nav>

        <main>
          <MarketplaceView
            marketplaceId="my-marketplace"
            layout="grid"
            productsPerPage={12}
          />
        </main>
      </div>
    </CartProvider>
  )
}

Vendor Dashboard

import React from 'react'
import {
  CartProvider,
  ConnectWalletButton,
  VendorDashboard,
  ProductForm,
  AnalyticsChart,
} from '@cartdotfun/react'

function VendorApp() {
  return (
    <CartProvider network="devnet">
      <div className="app">
        <header>
          <h1>Vendor Dashboard</h1>
          <ConnectWalletButton />
        </header>

        <main>
          <VendorDashboard
            tabs={['products', 'orders', 'analytics', 'settings']}
            initialTab="products"
          />
        </main>
      </div>
    </CartProvider>
  )
}

For more detailed information, visit the following resources:

Resources

GitHub Repository

Source code and examples

Component Storybook

Interactive component documentation

API Reference

Detailed API documentation

Example Applications

Complete example applications

Was this page helpful?