Next.js Swiper slide has full width before width calculation

55 views Asked by At

I have a code below:

'use client';
import { Swiper, SwiperSlide } from 'swiper/react';
import 'swiper/css';
import 'swiper/css/pagination';

export default function Component() {
  const cards = [{ id: 0 }, { id: 1 }, { id: 2 }];
  
  return (
    <Swiper
      slidesPerView={3}
      spaceBetween={30}
      className="mySwiper"
    >
      {cards.map((card) => (
        <SwiperSlide key={card.id}>
          <div className="h-52 bg-gray-400">{card.id}</div>
        </SwiperSlide>
      ))}
    </Swiper>
  )
}

The problem: Slides has full width before swiper calculate their width image before

after a few seconds the width will be set and the slides will look as I expected image after

What should I do to create slides at their original width and avoid UI flickering?

I tried setting a fixed width for slide but it didn't help

1

There are 1 answers

4
Kobra On BEST ANSWER

This happens because the images and the Swiper are not mounted yet, so you need to set a loading state while the component is mounting.

You can do this by creating a skeleton that gets the place of the Swiper while a state from useState is true and using useEffect() to turn that state to false, so when the component loads the skeleton gets out and the Swiper component enters in place.

Or only load the Swiper when the component is mounted, but it will get an ugly UI and bad UX.

You can use Suspense and loading.tsx too if you use a component that have async actions, but that is not your case.