Course contentsShow
← React Native
Lesson 196 of 1,5553. Core Primitive ComponentsFree lesson

Creating Carousel Image Viewers

Learners will implement horizontal paging interfaces for browsing image galleries.

In this lesson, you will learn how to build a smooth, horizontal image gallery where users can swipe through photos using the FlatList component.

The Core Concept

A carousel is essentially a FlatList that flows horizontally rather than vertically. By configuring the component to snap to the size of the screen, we create that familiar, polished "paging" effect found in popular photo apps. Instead of infinite scrolling, the list acts as a set of distinct "pages," each containing a single image.

Building the Carousel

To transform a standard list into a carousel, we need three specific properties on our FlatList:

  1. horizontal: Sets the layout direction to left-to-right.
  2. pagingEnabled: This is the secret sauce—it tells the list to "snap" to the edges of the screen rather than scrolling freely.
  3. showsHorizontalScrollIndicator: Usually set to false to keep the UI clean.

Here is how you implement it:

import { FlatList, Image, Dimensions, StyleSheet } from 'react-native';

const { width } = Dimensions.get('window');

const Carousel = ({ images }) => {
  return (
    <FlatList
      data={images}
      horizontal
      pagingEnabled
      showsHorizontalScrollIndicator={false}
      keyExtractor={(item) => item.id}
      renderItem={({ item }) => (
        <Image 
          source={{ uri: item.url }} 
          style={{ width, height: 300 }} 
        />
      )}
    />
  );
};

Why This Matters

By using the device's Dimensions, we ensure that every image takes up exactly 100% of the screen width. When the user drags their finger, the pagingEnabled prop detects the momentum and automatically "snaps" the view to the next image in the sequence. This provides a tactile, predictable experience for the user, preventing them from stopping halfway between two images.

Combined with the image optimization strategies we covered previously, this creates a performant and professional image browsing experience.

Key Takeaway: Use horizontal combined with pagingEnabled on a FlatList to create a snapping, screen-by-screen image carousel.