React-Swiper does not render slides on SSR when virtual slides are enabled
See original GitHub issueThis is a (multiple allowed):
-
bug
-
enhancement
-
feature-discussion (RFC)
-
Swiper Version: 6.3.2
-
Platform/Target and Browser Versions: macOS 10.15.6, Chrome 85.0.4183.121, Node v14.12.0, React 16.13.1.
What you did
On a page I’m building with React/Gatsby, I’ve added Swiper React component and enabled the virtual option to virtualize the slides.
import SwiperCore from 'swiper';
import { Swiper, SwiperSlide } from 'swiper/react';
import React, { CSSProperties, useCallback, useMemo, useState } from 'react';
export interface SlideData {
[key: string]: any;
id: string | number;
image: UnifiedImage;
imageAlt?: string | null;
}
export interface ImageSliderProps {
transitionSpeed: number;
slides: SlideData[];
}
const ImageSlider: React.FC<ImageSliderProps> = ({ slides, transitionSpeed}) => {
const [swiper, setSwiperLocal] = useState<SwiperCore | null>(null);
const swiperParams: Swiper = useMemo(
() => ({
allowTouchMove: true,
grabCursor: true,
lazy: false,
longSwipesRatio: 0.38,
onSwiper: setSwiperLocal,
parallax: true,
preloadImages: false,
roundLengths: true,
slidesPerView: 1,
speed: transitionSpeed,
}),
[transitionSpeed, setSwiperLocal],
);
return (
<Swiper {...swiperParams} virtual>
{slides.map((data, index) => (
<SwiperSlide
key={data.id}
virtualIndex={index}
>
<ImageSlideItem
alt={data.imageAlt}
image={data.image}
index={index}
/>
</SwiperSlide>
))}
</Swiper>
);
};
However, when I inspect the html output generated by SSR, no slides are prerendered. The slides get rendered only after rehydration/rerender of the react app, which is not ideal from a SEO/loading performance/UX perspective (the content of slides might not get indexed by search engines, and the browser can only start to download images in the slides after the whole react app has been rehydrated/rerendered. Also no content is shown to the user until the react app has been rehydrated/rerendered).
SSR output:
<div class="hero-slider__SliderRoot-sc-1tlus63-1 bHovIv">
<div class="swiper-container">
<div class="swiper-wrapper"></div>
</div>
</div>
Expected Behavior
Virtualized slides should be rendered during SSR in the same way as they will be rendered on the initial render of the react app in the browser
Actual Behavior
Virtualized slides don’t get rendered during SSR. If I remove the virtualize option, the slides get properly rendered.
Issue Analytics
- State:
- Created 3 years ago
- Comments:9 (1 by maintainers)
You can just use
next/dynamic
feature to dynamic import your components, so will not have this ssr problem.See details on next.js documents Dynamic Import
It is by design, virtual slides feature uses
useEffect
so it won’t work with SSR