Closed Hooman-studio closed 7 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>
);
}
Nice, thank you @osseonews!
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).