Course contentsShow
← React Native
Lesson 297 of 1,5554. Flexbox and Native StylingFree lesson

Masonry-Style Layouts

Implement non-linear content flow using absolute positioning or calculated column distributions.

Building Masonry-Style Layouts

In this lesson, you will learn how to break away from rigid rows and columns to create "Masonry" layouts, where items of varying heights are packed efficiently like bricks in a wall.

Standard Flexbox in React Native works on a linear flow: items fill a row before wrapping to the next. This creates "gaps" if one item is significantly taller than its neighbors. To achieve a true Masonry look, where items stack underneath the shortest available column, we must bypass the standard flow.

The Column Distribution Strategy

The most accessible way to build this as a beginner is to use calculated column distributions. Instead of one large container, you create two or more side-by-side vertical columns (Flex containers). You then sort your data items into these columns based on their index (e.g., all even-indexed items in column A, odd-indexed in column B).

const Masonry = ({ data }) => {
  const leftColumn = data.filter((_, i) => i % 2 === 0);
  const rightColumn = data.filter((_, i) => i % 2 !== 0);

  return (
    <View style={{ flexDirection: 'row' }}>
      <View style={{ flex: 1 }}>
        {leftColumn.map(item => <Card key={item.id} {...item} />)}
      </View>
      <View style={{ flex: 1 }}>
        {rightColumn.map(item => <Card key={item.id} {...item} />)}
      </View>
    </View>
  );
};

Why this works

By splitting the data into pre-determined columns, you force the content to flow vertically within its own stack. This eliminates the "dead space" caused by standard Flex wrapping. Because each column is a View with flex: 1, they share the screen width equally.

Important Considerations

  • Absolute Positioning: For more advanced control where you want items to "float" into gaps regardless of index, you can use absolute positioning. By calculating the top and left coordinates of each item based on the heights of previous elements, you can place them anywhere on the screen coordinate system.
  • Preventing Layout Shift: Since items have varying heights, ensure your images or cards have fixed aspect ratios or defined heights (as taught in our earlier lesson on "Preventing Layout Shift") to keep the layout stable as items render.

Key Takeaway: Masonry layouts are best achieved by mapping data into independent vertical column containers, allowing items to stack based on individual height rather than row-based constraints.