tezvyn:

Flexbox: Responsive Layouts in React Native

AI-drafted, machine-checkedSource: reactnative.devbeginner

Flexbox arranges components along a primary axis, creating responsive UIs without manual calculations. It's used for nearly all layout needs, from centering items to building complex grids.

WHY IT EXISTS Mobile apps must look good on countless screen sizes. Hardcoding pixel values for position and size is brittle and leads to broken layouts. Flexbox was adopted to provide a consistent and flexible algorithm for arranging elements that automatically adapts to the available space.

THE MENTAL MODEL Imagine your UI components are blocks inside a container. Flexbox gives you two main levers: a primary axis (the flexDirection) and a cross axis. You then use properties like justifyContent to distribute the blocks along the primary axis and alignItems to align them along the cross axis. The flex property on a child determines how much it grows relative to its siblings to fill the available space.

HOW IT WORKS You apply Flexbox properties to a container component's style to control its direct children. The three most common properties are flexDirection, justifyContent, and alignItems. flexDirection sets the main axis, either 'column' (top-to-bottom, the default) or 'row' (left-to-right). justifyContent aligns children along that main axis (e.g., 'center', 'space-between'). alignItems aligns children on the cross axis (e.g., 'center', 'stretch'). The flex property, applied to a child, makes it expand to fill available space. A child with flex: 2 will take twice as much space as a sibling with flex: 1.

WHEN TO USE IT Use Flexbox for virtually all layout tasks in React Native. It's the standard for structuring screens, positioning buttons, creating lists, and building any UI that needs to be responsive. It is the primary tool for distributing space among components or aligning them within a container.

WHEN NOT TO USE IT While Flexbox is the default, for positioning an element outside the normal layout flow, like a floating action button or a modal overlay, you would use position: 'absolute'. For very complex grid layouts that don't fit a single-axis model, you might reach for a third-party library, but Flexbox can handle most cases surprisingly well.

ONE CANONICAL EXAMPLE To perfectly center a child component inside a parent container, give the parent container these styles: flex: 1, justifyContent: 'center', and alignItems: 'center'. flex: 1 makes the container fill all available space. Since the default flexDirection is 'column', justifyContent: 'center' centers the child vertically. alignItems: 'center' then centers it horizontally along the cross axis. This three-property combination is a fundamental pattern for centering content.

Read the original → reactnative.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.