vercel / commerce

Next.js Commerce
https://demo.vercel.store
MIT License
11.48k stars 4.24k forks source link

Feature Request: Change Price and Image when selecting variant #1297

Closed Hooman-studio closed 7 months ago

Hooman-studio commented 9 months ago

Currently when selecting a variant on the product page it doesn't change either the price nor the image.

It would be great for this template to have the functionality to show the image of that variant when it is selected and also show the correct price. (not just in the cart but on the product page itself).

osseonews commented 9 months ago

You can get the details about the variant, by using a component, like below, and then just place the component where you want the variant details to show on the product page. Place this component in the components/product folder. Note: I only selected the price below to create a specific component for price. If you want more variant details, you will have to get it in the query and assign it properly, and then create another compoment.

'use client';
import { ProductVariant } from 'lib/shopify/types';
import { useSearchParams } from 'next/navigation';
import Price from 'components/price';
export function VariantPrice({
  variants,
}: {
  variants: ProductVariant[];
}) {

  const searchParams = useSearchParams();
  //if there are variants, then the default variant is the first one
  const defaultVariantId = variants.length ? variants[0]?.id : undefined;
  //console.log ("default", defaultVariantId)
  const variant = variants.find((variant: ProductVariant) =>
    variant.selectedOptions.every(
      (option) => option.value === searchParams.get(option.name.toLowerCase())
    )
  );
  const selectedVariantId = variant?.id || defaultVariantId;
  const filteredVariant = variants.filter(item => item.id === selectedVariantId)
  return (

     <div>
       {filteredVariant && filteredVariant.length > 0 ? (
         <Price
           amount={filteredVariant[0]?.price?.amount ?? ""}
           currencyCode={filteredVariant[0]?.price?.currencyCode ?? "USD"}
         />
       ) : "No Price"}
     </div>

  );
}
leerob commented 7 months ago

Nice, thank you @osseonews!