Example - Add to cart button (PDP)

Add the currently-viewed product variant to cart using productId and variantId from page parameters.

This example shows a basic "Add to cart" button on a product page.

It reads productId and variantId from the current page context and calls useActions().addToCart(...).

Code

import * as React from 'react';
import { Button, Text } from '@tapcart/mobile-components';

export default function AddToCartButtonExample({ pageState, useActions, useSearchParams }) {
  const { addToCart } = useActions();
  const searchParams = useSearchParams();

  const productId = searchParams.get('productId') || pageState?.searchParams?.productId;
  const variantId = searchParams.get('variantId') || pageState?.searchParams?.variantId;

  const [isAdding, setIsAdding] = React.useState(false);

  const handleAdd = async () => {
    if (!productId || !variantId) return;

    setIsAdding(true);
    try {
      await addToCart({
        lines: [
          {
            productId,
            variantId,
            quantity: 1,
          },
        ],
      });
    } finally {
      setIsAdding(false);
    }
  };

  const disabled = isAdding || !productId || !variantId;

  return (
    <div style={{ padding: '16px' }}>
      {!productId || !variantId ? (
        <Text type="body">This block is intended for a product page.</Text>
      ) : null}

      <Button onClick={handleAdd} disabled={disabled}>
        {isAdding ? 'Adding…' : 'Add to cart'}
      </Button>
    </div>
  );
}

Manifest

[]

Notes

  • This example assumes it’s placed on a product page (PDP) where productId and variantId are present in the page params.
  • To add line item properties, include attributes on the line item.

Back to Examples