From 68bcec868c596d9a47fe029a2eff90dcaa921ae5 Mon Sep 17 00:00:00 2001 From: Vladimir Kharlampidi Date: Thu, 27 Jan 2022 16:28:18 +0300 Subject: [PATCH] fix(react): compat with React 18 strict mode fixes #5398 --- src/react/{init-swiper.js => mount-swiper.js} | 7 +------ src/react/swiper.js | 14 +++++++++++--- 2 files changed, 12 insertions(+), 9 deletions(-) rename src/react/{init-swiper.js => mount-swiper.js} (84%) diff --git a/src/react/init-swiper.js b/src/react/mount-swiper.js similarity index 84% rename from src/react/init-swiper.js rename to src/react/mount-swiper.js index be4c5c556..3a171fd4c 100644 --- a/src/react/init-swiper.js +++ b/src/react/mount-swiper.js @@ -1,10 +1,5 @@ -import Swiper from 'swiper'; import { needsNavigation, needsPagination, needsScrollbar } from './utils.js'; -function initSwiper(swiperParams) { - return new Swiper(swiperParams); -} - function mountSwiper({ el, nextEl, prevEl, paginationEl, scrollbarEl, swiper }, swiperParams) { if (needsNavigation(swiperParams) && nextEl && prevEl) { swiper.params.navigation.nextEl = nextEl; @@ -23,4 +18,4 @@ function mountSwiper({ el, nextEl, prevEl, paginationEl, scrollbarEl, swiper }, swiper.init(el); } -export { initSwiper, mountSwiper }; +export { mountSwiper }; diff --git a/src/react/swiper.js b/src/react/swiper.js index 8d53f84c7..4daf39386 100644 --- a/src/react/swiper.js +++ b/src/react/swiper.js @@ -1,6 +1,7 @@ import React, { useRef, useState, useEffect, forwardRef } from 'react'; +import SwiperCore from 'swiper'; import { getParams } from './get-params.js'; -import { initSwiper, mountSwiper } from './init-swiper.js'; +import { mountSwiper } from './mount-swiper.js'; import { needsScrollbar, needsNavigation, @@ -57,11 +58,11 @@ const Swiper = forwardRef( }, }); - if (!swiperElRef.current) { + const initSwiper = () => { // init swiper Object.assign(swiperParams.on, events); eventsAssigned = true; - swiperRef.current = initSwiper(swiperParams); + swiperRef.current = new SwiperCore(swiperParams); swiperRef.current.loopCreate = () => {}; swiperRef.current.loopDestroy = () => {}; if (swiperParams.loop) { @@ -78,6 +79,10 @@ const Swiper = forwardRef( extend(swiperRef.current.params.virtual, extendWith); extend(swiperRef.current.originalParams.virtual, extendWith); } + }; + + if (!swiperElRef.current) { + initSwiper(); } // Listen for breakpoints change @@ -119,6 +124,9 @@ const Swiper = forwardRef( externalElRef.current = swiperElRef.current; } if (!swiperElRef.current) return; + if (swiperRef.current.destroyed) { + initSwiper(); + } mountSwiper( {