I have been looking for a way to make my Swiper.js
carousel responsive when it's nesting the Youtube React Player
. I finally found a workaround and hope this helps somebody. This also works if the slidesPerView
is more than 2 or even float number like slidesPerView={1.3}
.
Remove the default css mySwiper
class, and apply player-wrapper
and react-player
css as below.
The point is that the player-wrapper
div is self close and does not wrap the <ReactPlayer>
component. Also have the width
and height
props to be 100%
in the <ReactPlayer>
component.
<Swiper
slidesPerView={1.3}
grabCursor={false}
loop={false}
watchSlidesProgress={true}
centeredSlides={true}
modules={[Pagination, Navigation]}
// className='mySwiper' <=remove
>
<SwiperSlide>
<div className='player-wrapper' /> //<= self close div
<ReactPlayer
url='youtube.com/1234'
controls={true}
width='100%'
height='100%'
playing={isPlaying === data.id}
config={{
youtube: {
playerVars: { showinfo: 1 },
},
}}
className='react-player'
/>
</SwiperSlide>
CSS
.player-wrapper {
position: relative;
padding-top: 56.25%
}
.react-player {
position: absolute;
top: 0;
left: 0;
}