how to use onClick in react slick

3.7k Views Asked by At

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

3

There are 3 best solutions below

2
On

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

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

CodeBox link: working code

0
On

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>;
1
On

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