I'm trying to use my component within SwiperSlide
: using this directly inside it does work:
<Swiper>
<SwiperSlide>
<img src="https://swiperjs.com/demos/images/nature-1.jpg" />
</SwiperSlide>
</Swiper>
but if do something like:
const Foo = () =>
<SwiperSlide>
<img src="https://swiperjs.com/demos/images/nature-3.jpg" />
</SwiperSlide>
;
<Swiper>
<Foo />
</Swiper>
it doesn't work. later on I found this works:
<Swiper>
{Foo()}
</Swiper>
but i'd to fix and use <Foo />
properly, if possible.
full code:
import React, { useRef, useState } from "react";
// Import Swiper React components
import { Swiper, SwiperSlide } from "swiper/react";
// Import Swiper styles
import "swiper/css";
import "swiper/css/pagination";
import "swiper/css/navigation";
import "swiper/css/navigation";
import "swiper/css/effect-fade";
import "./styles.css";
// import required modules
import { EffectFade, Autoplay, Pagination, Navigation } from "swiper";
export default function App() {
return (
<>
<Swiper
effect={"fade"}
loop={true}
navigation={true}
spaceBetween={30}
centeredSlides={true}
autoplay={{
delay: 5000,
disableOnInteraction: false,
pauseOnMouseEnter: true
}}
pagination={{
clickable: true
}}
modules={[EffectFade, Autoplay, Pagination, Navigation]}
className="mySwiper"
>
<SwiperSlide>
<img src="https://swiperjs.com/demos/images/nature-1.jpg" />
</SwiperSlide>
<Foo />
</Swiper>
</>
);
}
const Foo = () => (
<SwiperSlide>
<img src="https://swiperjs.com/demos/images/nature-2.jpg" />
</SwiperSlide>
);
live example here
what am I missing? How do I fix that?
CodePudding user response:
This is because Foo is not a proper jsx component. Rewrite as below.
const FooComponent = () => {
return (
<SwiperSlide>
<img src="https://swiperjs.com/demos/images/nature-3.jpg" />
</SwiperSlide>
);
};
Code Sandbox : https://codesandbox.io/s/patient-resonance-uz8un9?file=/src/App.js:171-320
CodePudding user response:
Probably swiper needs SwiperSlide to be a child of Swiper. Your code is injecting a middle element <Foo />
beetween those two in the VDOM. I'm not sure how to do that abstraction, but probable you will need to add the SwiperSlide component on every item and do the abstraction with its childs