skip to Main Content

I am developing an ecommerce application and on productdetail page my main image is showing previous state ..only updates on refreshing page

 const [mainImage,setMainImage] = useState(images[0])



return (
 <div className="productdisplay-img-left">
   {(images.length > 1) && (
    images.map((image,index)=>(
      <img key={index} onClick={()=>setMainImage(image)} src={`http://localhost:3000/public/products/${image}`}/>
    ))
   )}
  </div>
<div className="productdisplay-main-img">
 <img src={`http://localhost:3000/public/products/${mainImage}`}/>
                
</div>
)

2

Answers


  1. The code you’ve provided looks mostly correct, but it’s likely a problem with the state not updating properly or the event handling of the click event. Create a function that call on onClick event in the images.map()

    const ProductDetail = ({ images }) => {
      const [mainImage, setMainImage] = useState(images[0]);
    
      const handleImageClick = (image) => {
        setMainImage(image);
      };
    
      return (
        <div className="productdisplay-img-left">
          {images.length > 1 &&
            images.map((image, index) => (
              <img
                key={index}
                onClick={() => handleImageClick(image)}
                src={`http://localhost:3000/public/products/${image}`}
                alt={`Product ${index}`}
              />
            ))}
        </div>
        <div className="productdisplay-main-img">
          <img src={`http://localhost:3000/public/products/${mainImage}`} alt="Main Product" />
        </div>
      );
    };
    
    Login or Signup to reply.
  2. Try this one to resolve the issue :

       const [mainImage, setMainImage] = useState(images[0]);
        
      
        useEffect(() => {
          setMainImage(images[0]); 
        }, [images]);
        
        return (
          <div className="productdisplay-img-left">
            {images.length > 1 &&
              images.map((image, index) => (
                <img
                  key={index}
                  onClick={() => setMainImage(image)}
                  src={`http://localhost:3000/public/products/${image}`}
                />
              ))}
          </div>
          <div className="productdisplay-main-img">
            <img src={`http://localhost:3000/public/products/${mainImage}`} />
          </div>
        );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search