I’m having a little problem
I want every time I click on an image, my main image will change according to the image that I click on
I want to click on the image below, the image above changes
this is my code
import React from "react";
const SingleProductComponent = ({ list }) => {
return (
<div className="col-12 col-sm-12 col-md-6 col-lg-6 col-xl-6">
<div className="SingProduct__img">
<div className="SingProduct__inner">
<div className="inner__data">
{list.image && (
<img
src={list.image[0]}
alt=""
className="inner__data-img"
/>
)}
</div>
</div>
{list.image && (
<div className="SingleProduct__thumb">
<div className="SingleProduct__thumb-list">
{list.image.map((e, index) => (
<div className="thumb__list-item" key={index}>
<img src={e} className="thumb__item-img" alt="" />
</div>
))}
</div>
</div>
)}
</div>
</div>
)
}
>Solution :
You need to set a state to the selected image index, and then according to the clicked item, you change the value.
import React, {useState} from "react";
const SingleProductComponent = ({ list }) => {
const [selectedIndex, setSelectedIndex] = useState(0);
const changeSelectedItem = (index) => {
setSelectedIndex(index)
}
return (
<div className="col-12 col-sm-12 col-md-6 col-lg-6 col-xl-6">
<div className="SingProduct__img">
<div className="SingProduct__inner">
<div className="inner__data">
{list.image && (
<img
src={list.image[selectedIndex]}
alt=""
className="inner__data-img"
/>
)}
</div>
</div>
{list.image && (
<div className="SingleProduct__thumb">
<div className="SingleProduct__thumb-list">
{list.image.map((e, index) => (
<div className="thumb__list-item" key={index} onClick={() => changeSelectedItem(index)}>
<img src={e} className="thumb__item-img" alt="" />
</div>
))}
</div>
</div>
)}
</div>
</div>
)
}
