react-native-web-swiper
react-native-web-swiper copied to clipboard
Possible to add slides dynamically?
I know this project is not being actively maintained and added to. I totally get that. But I have a question about what it currently supports.
In my project I need to dynamically add slides. As one slide is being experienced, new slides are being pulled in from the server.
I can't get it to work. At first, when I add slides, Swiper does not seem to pick them up. The only way I can get the Swiper component to pick up the new slides is by adding a key
prop to Swiper and changing the key each time a new slide is added. But by changing Swiper's key, it has the side effect of forcing Swiper to completely tear down and re-initiate every slide within it. This does pick up the new slides, but it completely disrupts where the user was at since it resets the swiper experience back to the beginning.
Am I doing something wrong? Is there a way to get it to detect new slides without impacting the existing ones? This is my key code:
<Swiper
vertical
ref={swiperRef}
>
{props.slides.map((slide: slide) => {
return <SlideView slide={slide} key={slide.id} />
})}
</Swiper>
Hi! Adding children dynamically without re-mounting the children is currently not supported unfortunately :(
@jarvisluong I got it working in my own branch. It was a simple change. You were taking the props.slides and turning it into a constant at the top of the component. I just did a find & replace to keep addressing props.slides throughout the component and then dynamic slides "just works." It was nice how easy of a fix that was.
@jarvisluong I got it working in my own branch. It was a simple change. You were taking the props.slides and turning it into a constant at the top of the component. I just did a find & replace to keep addressing props.slides throughout the component and then dynamic slides "just works." It was nice how easy of a fix that was.
Would you mind submitting a PR?
For anyone looking for a solution, go to the swiper.js,
Replace this line:
children = (() => React.Children.toArray(this.props.children))();
with this line:
children = (() => React.Children.toArray(this.props.slides))();
now, you can do:
<Swiper slides=[<View/>, <View/>] etc. (dynamic)
Don't forget to rebuild the package after that.
Hope that helps.
The issue seems to be stale. I will close this for now.
You can use key props. If the key changes, component unmount and remount.
const swiperKey = props.banners.length > 0 ? props.banners.join() : '0';
<View style={{ width: CAROUSEL_WIDTH, height: CAROUSEL_HEIGHT, backgroundColor: '#000000' }} key={swiperKey}> <Swiper> {props.banners.map(banner => ( <Image source={{ uri: ``, }} style={{ width: '100%', height: '100%' }} /> ))} <Text>4</Text> </Swiper> </View>