पाठ 4 / 25

StyleSheet and Flexbox

Styles as objects, column by default.

Style props and Flexbox defaults

Every core component accepts a style prop: an object (or array of objects) with camelCased names such as backgroundColor and marginTop. Numbers are density-independent pixels; there are no units like px or rem. StyleSheet.create groups styles and gives you validation and editor help. Layout uses Flexbox (implemented by the Yoga engine), but with mobile defaults: flexDirection defaults to column, alignContent to flex-start, and flex accepts a single number. Styles do not cascade, except that nested Text inherits some text styles from its parent Text. In an array, later styles override earlier ones, which is handy for conditional styles.

Flexbox everywhere

Styles are JavaScript objects and layout is Flexbox, with some mobile-specific defaults and screen concerns.

Three ideas: StyleSheet and Flexbox, responsive layouts with safe areas, platform-specific code.
Figure 2.1 — Styles, flex layout and screen edges.

A header row

StyleSheet with a row layout and a conditional style.

import { StyleSheet, View, Text } from "react-native";

export function Header({ title, active }: { title: string; active: boolean }) {
  return (
    <View style={styles.row}>
      <Text style={[styles.title, active && styles.active]}>{title}</Text>
      <View style={styles.badge} />
    </View>
  );
}

const styles = StyleSheet.create({
  row: {
    flexDirection: "row",        // default is "column"
    justifyContent: "space-between",
    alignItems: "center",
    paddingHorizontal: 16,
    height: 56,
  },
  title: { fontSize: 18, color: "#111827" },
  active: { color: "#2563eb", fontWeight: "700" },
  badge: { width: 10, height: 10, borderRadius: 5, backgroundColor: "#22c55e" },
});

A stack of plates

By default children stack top to bottom like plates on a shelf. Switching to flexDirection row lays them side by side like books.

त्वरित जाँच: What is the default flexDirection in React Native?

  • row
  • column
  • row-reverse
  • There is no Flexbox in React Native
Answer

column — Mobile screens are usually vertical, so children stack vertically.