@@ -29,6 +29,7 @@ const ProductDetailPage: React.FC<ProductDetailPageProps> = ({ product }) => {
2929 ) ;
3030 const [ selectedOptions , setSelectedOptions ] = useState < Record < string , string > > ( { } ) ;
3131 const [ quantity , setQuantity ] = useState ( 1 ) ;
32+ const [ selectedImageIndex , setSelectedImageIndex ] = useState ( 0 ) ;
3233
3334 // Show loading state while page is being generated
3435 if ( router . isFallback ) {
@@ -78,6 +79,16 @@ const ProductDetailPage: React.FC<ProductDetailPageProps> = ({ product }) => {
7879
7980 if ( matchingVariant ) {
8081 setSelectedVariant ( matchingVariant ) ;
82+
83+ // Update image if variant has an associated image
84+ if ( matchingVariant . image ) {
85+ const imageIndex = product . images . edges . findIndex (
86+ ( { node } ) => node . id === matchingVariant . image ?. id
87+ ) ;
88+ if ( imageIndex !== - 1 ) {
89+ setSelectedImageIndex ( imageIndex ) ;
90+ }
91+ }
8192 }
8293 } ;
8394
@@ -101,7 +112,7 @@ const ProductDetailPage: React.FC<ProductDetailPageProps> = ({ product }) => {
101112 }
102113 } ;
103114
104- const currentImage = selectedVariant ?. image || product . images . edges [ 0 ] ?. node ;
115+ const currentImage = product . images . edges [ selectedImageIndex ] ?. node || product . images . edges [ 0 ] ?. node ;
105116 const price = selectedVariant ?. price || product . priceRange . minVariantPrice ;
106117 const compareAtPrice = selectedVariant ?. compareAtPrice ;
107118
@@ -179,18 +190,10 @@ const ProductDetailPage: React.FC<ProductDetailPageProps> = ({ product }) => {
179190 { /* Thumbnail Gallery */ }
180191 { product . images . edges . length > 1 && (
181192 < div className = "tw-grid tw-grid-cols-4 tw-gap-4 tw-mt-4" >
182- { product . images . edges . map ( ( { node : image } ) => (
193+ { product . images . edges . map ( ( { node : image } , index ) => (
183194 < button
184195 key = { image . id }
185- onClick = { ( ) => {
186- // Find variant with this image
187- const variantWithImage = product . variants . edges . find (
188- ( { node } ) => node . image ?. id === image . id
189- ) ?. node ;
190- if ( variantWithImage ) {
191- setSelectedVariant ( variantWithImage ) ;
192- }
193- } }
196+ onClick = { ( ) => setSelectedImageIndex ( index ) }
194197 className = { clsx (
195198 "tw-rounded-lg tw-overflow-hidden tw-border-2 tw-transition-all" ,
196199 currentImage . id === image . id
0 commit comments