swiper: Using breakpoints option in Next JS causes Hydration error
Discussed in https://github.com/nolimits4web/swiper/discussions/5776
<div type='discussions-op-text'>Originally posted by Sakkhor909 June 7, 2022 First of all, thank you for this amazing library.
Everything works fine until I use breakpoints
import { Swiper, SwiperSlide } from "swiper/react";
import Image from "next/image";
<Swiper
slidesPerView={1}
breakpoints={{
1024: {
slidesPerView: 3,
},
}}
>
{Data.images.map((imgSrc, index) => {
return (
<SwiperSlide>
<Image src={imgSrc} alt={Data.name + index} layout="fill" />
</SwiperSlide>
);
})}
</Swiper>
The error is shown on the next js page
Error: Hydration failed because the initial UI does not match what was rendered on the server.
</div>About this issue
- Original URL
- State: closed
- Created 2 years ago
- Reactions: 30
- Comments: 25
Using
slidesPerView="auto"
fixed the issue for me.Sample Code for reference
Than same issue with me also
Thank you for the solution. It works.
Thank you for this, I feel this is the best solution on this thread!
I made some small simplifications:
` const [customSwiperOptions, setCustomSwiperOptions] = useState(null);
useEffect(() => { const options = { 640: { slidesPerView: 2, spaceBetween: 20, }, 768: { slidesPerView: 2, spaceBetween: 20, }, 1024: { slidesPerView: 3, spaceBetween: 20, }, 1200: { slidesPerView: 4, spaceBetween: 20, }, } setCustomSwiperOptions(options); }, [])
const testimonialCarousel = { slidesPerView: 1, spaceBetween: 20, loop: true, speed: 1000, centeredSlides: true, autoHeight: true, modules: [Autoplay], autoplay: { waitForTransition: false, delay: 4000, }, breakpoints: customSwiperOptions };
Even if we keep swiper client side, isn’t it causing a huge CLS ?
If you decide to use
slidesPerView="auto"
you have to take into account that you have to control the CLS (Web Vitals) since doing this causes the images to move, in the first render they will be loaded automatically while in the next one it will exist a design change.I want to have a bit of the next slide peaking on the screen, so slidesPerView=auto won’t work for me- any other ideas or possible fixes you came up with?
I don’t know is it dirty or not? but i fixed it by the code :
This actually makes sense. Your static build created the HTML without a screensize, so the default settings are run. When your JS runs for the first time, it will consider breakpoints, thus creating a mismatch in HTML elements.
This is my solution. I have used Tailwind CSS, and wrapped
Swiper
with one more div, and gavewidth: 100%
. it works okIs anyone still getting hydration error even after using slidesperview =“auto” ?
Just want to clarify here,
slidesPerView="auto"
is not a fix, it’s a workaround.