Search code examples
reactjsreact-slick

react slick when using map slider not working


why react slick slider not working when using this:

        <Slider className="mb-24" {...settings}>
          {
            mockEventInfoArr.map((el => (
                <div onClick={() => handleOpenEvent(el)}>
                  <li className="flex-center fd-col">
                    <p className="mb-12 fw-600 color-main">{el.name}</p>
                    <p className="fs-small">{formatRelative(el.start, new Date(), { locale })}</p>
                  </li>
                </div>


            )))
          }
        </Slider>

but when I use this it works...

        <Slider className="mb-24" {...settings}>

              <div onClick={() => handleOpenEvent()}>
                <li className="flex-center fd-col">
                  <p className="mb-12 fw-600 color-main">{'asdsda'}</p>
                  <p className="fs-small">{formatRelative(new Date(), new Date(), { locale })}</p>
                </li>
              </div>
    
              <div onClick={() => handleOpenEvent()}>
                <li className="flex-center fd-col">
                  <p className="mb-12 fw-600 color-main">{'asdsda'}</p>
                  <p className="fs-small">{formatRelative(new Date(), new Date(), { locale })}</p>
                </li>
              </div>
        </Slider>

What I am doing wrong ?

Here is an image where it looks like when I use map

enter image description here

€: Here are my settings

const settings = {
  dots: true,
  infinite: true,
  autoplay: true,
  speed: 1000,
  initalSlide: 1,
  autoplaySpeed: 5000,
  slidesToShow: 1,
  slidesToScroll: 1,
};

Solution

  • When using .map in react you need to have a unique key on each element within the map. You can use the index or uuid or any. The key in the map helps react and recognize the element and changes when re-rendering.

    <Slider className="mb-24" {...settings}>
        {mockEventInfoArr.map((el, i) => (
            <div key={i} onClick={() => handleOpenEvent(el)}>
                <li className="flex-center fd-col">
                    <p className="mb-12 fw-600 color-main">{el.name}</p>
                    <p className="fs-small">{formatRelative(el.start, new Date(), { locale })}</p>
                </li>
            </div>
        ))}
    </Slider>;