You already store the active index
in your state so you can use that. Although I would move that out and use a separate state for your products
array and for the active index
. And I'm not sure why you want to use ref
s here.
When you render the list of images, you can check if the currently rendered index is the same as the activeIndex
in your state. If it is, add the active
class name, if not, don't add anything. You don't need to store the previously selected index because when you map over the images, you only set the class for the selected one.
const ProductDetails = () => {
const [activeIndex, setActiveIndex] = useState(0);
const [products, setProducts] = useState([
{
_id: "1",
title: "Nike Shoes",
src: [
"https://www.upsieutoc.com/images/2021/01/07/img2.png",
"https://www.upsieutoc.com/images/2021/01/07/img3.png",
"https://www.upsieutoc.com/images/2021/01/07/img4.png",
],
},
]);
return (
<Container>
<Row>
{products.map((item) => (
<Colsm6 key={item._id}>
<ProductdetailsPic>
<Sync1>
<Item>
<img src={item.src[activeIndex]} alt="" />
</Item>
</Sync1>
<Sync2>
{item.src.map((img, i) => (
<Item>
<Itempro>
<img
src={img}
className={i === activeIndex ? 'active' : null}
alt=""
onClick={() => setActiveIndex(i)}
/>
</Itempro>
</Item>
))}
</Sync2>
</ProductdetailsPic>
</Colsm6>
))}
<Prosdetleft></Prosdetleft>
</Row>
</Container>
);
};
export default ProductDetails;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…