Swiper React cannot convert undefined or null to object
Asked Answered
C

2

8

I am using Swiper library to show image Slides and thumbnails. Whenever I click on a particular thumbnail, the image mapping to the thumbnail clicked should appear on view.

import { Swiper, SwiperSlide } from "swiper/react";
import { Navigation, Thumbs } from "swiper";
import "swiper/css";
import "swiper/css/navigation";
import "swiper/css/thumbs";
import "./swiper.css";
const SwiperImage = () => {
  const [activeThumb, setActiveThumb] = React.useState();
  return (
    <>
      <Swiper
        loop={true}
        spaceBetween={10}
        navigation={true}
        modules={[Navigation, Thumbs]}
        grabCursor={true}
        thumbs={{ swiper: activeThumb }}
        className="vehicle-image-slider"
      >
        {images.map((item, index) => (
          <SwiperSlide key={index}>
            <img src={item} alt="lamborgini image" />
          </SwiperSlide>
        ))}
      </Swiper>
      <Swiper
        onSwiper={setActiveThumb}
        loop={true}
        spaceBetween={10}
        slidesPerView={4}
        modules={[Navigation, Thumbs]}
        className="vehicle-image-slider-thumbs"
      >
        {images.map((item, index) => (
          <SwiperSlide key={index}>
            <div className="thumbs-wrapper">
              <img src={item} alt="lamborgini image" />
            </div>
          </SwiperSlide>
        ))}
      </Swiper>
    </>
  );
};

I tried using onSwiper prop to achieve this functionality but i ran into an error.

thumbs.js:67 Uncaught TypeError: Cannot convert undefined or null to object
    at Function.assign (<anonymous>)
    at Object.init (thumbs.js:67:1)
    at updateSwiper (update-swiper.js:92:1)
    at swiper.js:158:1
    at commitHookEffectLi

I can't seem to find anything wrong with my code as per the documentation.

Cofsky answered 20/7, 2022 at 6:23 Comment(2)
Probably a but in the library, there are workaround in this issueKora
After removing strict mode in my react application it works. However, I don't think this is a good solution to the problem.Cofsky
M
37

Add this.

thumbs={{swiper: thumbsSwiper && !thumbsSwiper.destroyed ? thumbsSwiper : null}}
Mckinnie answered 29/7, 2022 at 13:28 Comment(1)
this answer saved my day. thank you!Vani
A
0

I fix this issue with

import {SwiperClass } from "swiper/react"
const [thumbsSwiper, setThumbsSwiper] = React.useState<SwiperClass>()
Ambulant answered 6/2 at 14:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.