Custom Horizontal Auto Scroll Looped Carousel using scrollview

This post helps you to create a custom horizontal auto scrollable looped carousel using scrollview, This is how the end result looks like:

  • You can find many libraries for the same like react-native-snap-carousel , react-native-looped-carousel.

The carousel itself is easy — take a Scrollview, fill it with images and add the following properties to it:

We need to create a reference for the scrollview so we can use it for auto scroll. Different properties :-

1. pagingEnabled is used it to scroll one page at time if user interepts the autoscroll and scrolls itself.

2. snapToInterval provides the child width for pagination.

The basic idea behind a looped carousel is to make a never ending list. So how we going to achieve that?

To make a list as a never ending list, we should add first item of the list at the last. Now when it scrolls, it shows the first item after the last item.

To make it auto scrollable we need to setup a timer. Plus we need to increase the current index by one every time, so it continues to scroll. Now, when it reaches the last element, which is same as the first element, we made the scrollview to scroll to first position without adding any animation to it. To a user this feels like looking at the same item. Scrollview is now at 0th position and it continues to scroll with any interruption.

A small catch here!

What if a user interrupts the autoscroll?
We should be able to resume autoscroll from the same position upto which user has scrolled.

The idea is to get the current index of the child with the offset provided by the Scrollview. Once we calculate the current index, we can then resume.

Here is the code for Custom Carousel.

And this how we can use it as a reusable component.

Software developer at React Native