1

I am using react slick in my Websites. I have 4 slides. Every Slide, I want a onClick Function to get the value. But When I click on the Slide, I am getting the last value only. I searched Stack Overflow but can't find solutions.

Here's the Code:

const productSlideImg = [
  { Img: prodImg1, ImgName: "img1", pageLink: "/home" },
  { Img: prodImg2, ImgName: "img2", pageLink: "/about" },
  { Img: prodImg3, ImgName: "img3", pageLink: "/contact" }
];


const handleClickSlide = (item) => {
    console.log(item); // getting "img3" only on every slide click

  };


<Slider
    autoplay={true}
    slidesToShow={1}
    slidesToScroll={1} >

            {productSlideImg.map((item, index) => (
              <div   >
                <img
                  style={{ borderRadius: "50px" }}
                  width={"100%"}
                  src={item.Img}
                  onClick={() => {handleClickSlide(item.ImgName) }}
                 
                />
              </div>
            ))}

          </Slider>

Please help me with some solutions

soma iyappan
  • 482
  • 7
  • 16
  • you have a mistake on code, I think you are checking a wrong point of code, you define `handleClickProduts` function on code but you use `handleClickSlide` on `onClick` event!! – masoud Apr 28 '22 at 07:06

3 Answers3

1

you have created a different function handleClickProduts and using different function on img onClick

onClick={() => {handleClickProduts (item.ImgName) }}

CodeBox link: working code

RoshaanAli
  • 136
  • 1
  • 8
0

I found the solution hope the person reading this finds this helpful. So I was using fade=true in react slick props settings removing that RESOLVED the issue for me. See Attached Photo

iceeuwu
  • 1
  • 1
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 08 '23 at 07:57
0

I think your problem is that when you use array.map in react you need to add the key attribute. So in your case, you need to add the key in your div like this:

   <Slider autoplay={true} slidesToShow={1} slidesToScroll={1}>
    {productSlideImg.map((item, index) => (
      // adding the key attribute
      <div key={index}>
        <img
          style={{ borderRadius: "50px" }}
          width={"100%"}
          src={item.Img}
          onClick={() => {
            handleClickSlide(item.ImgName);
          }}
        />
      </div>
    ))}
  </Slider>;