Learn Expo · 2/11

Core Fundamentals & UI Basics

9 min read

Core Fundamentals & UI Basics 📱

Welcome to the building blocks of mobile development! If you have ever built a website, you are already halfway there. However, mobile devices are a completely different environment. They don't have web browsers interpreting your code natively, they don't use mice, and they have strict memory limitations.

Before we dive into the concepts, let's quickly set up our workspace using the latest industry standard.

The Setup (2026 Standard)
To start a modern Expo project, open your terminal and run:

bash
npx create-expo-app@latest my-mobile-app
cd my-mobile-app
npx expo start

This gives you the latest boilerplate. Now, let's replace those default files and learn how to actually build an interface.


1. Core Components: View, Text, and Image

The Problem

In web development, you build interfaces using HTML tags like <div>, <p>, and <img>. Mobile operating systems (iOS and Android) do not understand HTML. If you try to drop a <div> into a React Native file, the app will instantly crash because the underlying phone has no idea how to draw a "div" on the screen. We need a way to tell iOS to draw an iOS container, and Android to draw an Android container, using the exact same code.

The Solution: Native Core Components

React Native provides primitive components that automatically translate (compile) into their platform-specific native UI counterparts. You write JavaScript, and React Native bridges it to native code.

View

Definition: A fundamental UI building block that acts as a container to support layout, styling, and touch handling.

How it works: Whenever you need to group items together, create a box, or build a layout grid, you use a <View>. Under the hood, a <View> translates directly to a UIView on iOS and a ViewGroup on Android.

Text

Definition: A component used for displaying, styling, and nesting strings of text.

How it works: On the web, you can technically leave text floating inside a <div>. In React Native, all text must be wrapped inside a <Text> component. If you leave floating text outside of this component, you will get a fatal error.

Image (Industry Standard: expo-image)

Definition: A cross-platform React component that loads and renders images.

The Industry Shift: React Native has a built-in <Image> component, but handling heavy images, caching them so they don't reload every time, and preventing screen flickering is notoriously difficult with it. The industry standard is to use expo-image. It uses highly performant native libraries (SDWebImage for iOS and Glide for Android) under the hood to load images blazingly fast.

To use it, you install it via: npx expo install expo-image

Hands-on Example:

tsx
import { View, Text } from 'react-native';
import { Image } from 'expo-image'; // Notice we import Image from expo-image, not react-native!

export default function ProfileCard() {
  return (
    <View>
      <Image 
        source={{ uri: 'https://picsum.photos/200' }} 
        style={{ width: 100, height: 100 }} 
        contentFit="cover" // Replaces the old 'resizeMode'
        transition={1000} // Smooth 1-second fade-in
      />
      <View>
        <Text>John Doe</Text>
        <Text>Software Engineer</Text>
      </View>
    </View>
  );
}

2. Styling the React Native Way: StyleSheet and Flexbox

The Problem

You cannot use .css files in React Native. There is no CSS engine, no DOM, and no HTML classes. So, how do we make our apps look good without writing inline styles that clutter our code and ruin performance?

The Solution: StyleSheet and React Native Flexbox

StyleSheet

Definition: An API that allows you to create style objects, serving as an abstraction similar to CSS stylesheets.

How it works: Instead of writing CSS, you write JavaScript objects. The StyleSheet.create() method takes these objects, validates them, and sends them over the native bridge only once, which is highly efficient for performance.

React Native Flexbox

Definition: A layout algorithm designed to provide a consistent layout on different screen sizes.

Imagine you are organizing a bookshelf (the container). You have several books (the components) to place. You need a set of rules to decide if the books should stack vertically in a pile, or sit side-by-side. You also need rules to decide if they should be crammed to the left, centered, or spread out evenly. Flexbox is the set of rules you give to the bookshelf to automatically arrange your books.

Crucial Industry Difference:
If you know web CSS, you know flexDirection defaults to row (left to right). In React Native, mobile screens are tall and narrow. Therefore, flexDirection defaults to column (top to bottom).

Hands-on Example:

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

export default function StyledCard() {
  return (
    <View style={styles.container}>
      <View style={styles.card}>
        <Text style={styles.title}>Hello World</Text>
        <Text style={styles.subtitle}>Styling is fun!</Text>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1, // Takes up the entire available screen space
    backgroundColor: '#f3f4f6',
    justifyContent: 'center', // Centers children vertically (because default is column)
    alignItems: 'center',     // Centers children horizontally
  },
  card: {
    backgroundColor: 'white',
    padding: 20,
    borderRadius: 12, // Look! camelCase instead of border-radius
    shadowColor: '#000',
    shadowOpacity: 0.1,
    shadowRadius: 10,
    elevation: 5, // Android requires 'elevation' for shadows
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#111827',
  },
  subtitle: {
    fontSize: 16,
    color: '#6b7280',
    marginTop: 8,
  },
});

3. Handling User Input: TextInput, Buttons, and Pressables

The Problem

Users need to type data and tap on things. But we have a specific issue: standard buttons look entirely different on iOS versus Android. If you want a button to look exactly the same across both platforms, match your company's branding, and have custom animations when pressed, the built-in components fall short.

The Solution: TextInput and Pressable

TextInput

Definition: A foundational component for inputting text into the app via a keyboard.

How it works: You tie the input to a React state variable. When the user types, the state updates. When the state updates, the input reflects the text. This is called a "controlled component".

Button vs Pressable

Definition (Pressable): A core component wrapper that can detect various stages of press interactions on any of its defined children.

Why the industry ignores <Button>: The built-in <Button> component is rigid. It gives you a standard blue iOS text button on iPhones, and a solid colored native ripple button on Android. You cannot easily change its padding, border radius, or custom styles.
Instead, the industry heavily relies on <Pressable>. It allows you to wrap any View or Text and turn it into a highly customizable button that detects exactly when a user's finger goes down (onPressIn), goes up (onPressOut), or completes a tap (onPress).

Hands-on Example:

tsx
import { useState } from 'react';
import { View, Text, TextInput, Pressable, StyleSheet } from 'react-native';

export default function LoginForm() {
  const [email, setEmail] = useState('');

  const handleLogin = () => {
    console.log('Logging in with:', email);
  };

  return (
    <View style={styles.form}>
      <TextInput
        style={styles.input}
        placeholder="Enter your email"
        value={email}
        onChangeText={setEmail} // Automatically passes the typed string to state
        keyboardType="email-address" // Shows the @ symbol on the keyboard automatically
        autoCapitalize="none"
      />

      <Pressable 
        style={({ pressed }) => [
          styles.button, 
          pressed && styles.buttonPressed // Applies a different style when the finger is holding it down
        ]}
        onPress={handleLogin}
      >
        <Text style={styles.buttonText}>Log In</Text>
      </Pressable>
    </View>
  );
}

const styles = StyleSheet.create({
  form: { padding: 20 },
  input: {
    height: 50,
    borderColor: '#ccc',
    borderWidth: 1,
    borderRadius: 8,
    paddingHorizontal: 15,
    marginBottom: 15,
  },
  button: {
    backgroundColor: '#007AFF',
    height: 50,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 8,
  },
  buttonPressed: {
    opacity: 0.7, // Dims the button when pressed
    backgroundColor: '#005BB5',
  },
  buttonText: {
    color: 'white',
    fontWeight: 'bold',
    fontSize: 16,
  }
});

4. Scrolling Content: ScrollView vs. FlatList for Performance

The Problem

Mobile screens are small. If you have a list of 50 items, they will easily overflow the screen. A standard <View> does not scroll; the extra items just disappear into the void off-screen.
You might think, "I'll just wrap it in a scrolling container!" But if you have 10,000 items (like an Instagram feed) and you tell the phone to load all 10,000 items at once so they can be scrolled, the phone's memory will overflow, and the app will crash instantly.

The Solution: Use ScrollView for small things, and FlatList for large lists.

ScrollView

Definition: A generic scrolling container that can host multiple components and views.

How it works: It renders all of its child components at once, regardless of whether they are currently visible on the screen.
When to use it: Forms, settings pages, or articles. Use it when you have a small, known amount of content.

FlatList (The Virtualized List)

Definition: A performant interface for rendering basic, flat lists of data.

Imagine you are running a small drive-through window (the phone screen). You have 1,000 cars (the data) waiting in line down the block. If you tried to force all 1,000 cars into your tiny parking lot at once, everything would jam and break (memory crash). Instead, you only let 5 cars into the lot at a time. When one car drives away (scrolls off-screen), you let the next car enter. You are constantly reusing the same small parking space, no matter how many cars are waiting outside.

This concept is called Virtualization. FlatList only renders the items currently visible on the screen (plus a few extra just off-screen for smooth scrolling). As you scroll down, it unmounts the items that disappeared at the top, freeing up memory.

Key Props of FlatList:

  1. data: The array of information you want to render.
  2. renderItem: A function that takes a single piece of data from the array and returns a UI component.
  3. keyExtractor: A function that tells React Native how to uniquely identify each item (like a database ID).

Hands-on Example:

tsx
import { SafeAreaView, FlatList, View, Text, StyleSheet } from 'react-native';

// 1. The Data
const MOCK_DATA = Array.from({ length: 1000 }).map((_, index) => ({
  id: String(index),
  title: `List Item #${index + 1}`,
}));

// 2. The isolated UI Component for a single item
// Extracting this outside the main component prevents unnecessary re-renders!
const ItemCard = ({ title }: { title: string }) => (
  <View style={styles.item}>
    <Text style={styles.title}>{title}</Text>
  </View>
);

export default function InfiniteList() {
  return (
    // SafeAreaView ensures content doesn't hide behind the iPhone notch or Android status bar
    <SafeAreaView style={styles.container}>
      <FlatList
        data={MOCK_DATA}
        keyExtractor={(item) => item.id}
        renderItem={({ item }) => <ItemCard title={item.title} />}
        
        // Industry Performance Tweaks:
        initialNumToRender={10} // How many items to render on the first load
        maxToRenderPerBatch={10} // How many items to process per scroll chunk
        windowSize={5} // How many "screens" worth of data to keep in memory
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: '#fff' },
  item: {
    padding: 20,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  title: { fontSize: 16 },
});

(Fun Fact: If you find FlatList is still too slow for massive feeds with heavy images, the current industry powerhouse is FlashList by Shopify. It uses the exact same props as FlatList but recycles the UI components under the hood, making it up to 5x faster!)


📚 References & Further Reading

Challenge

Challenge: Build a User Profile Card Component

Your task is to build a functional and styled user profile card component in React Native. You must use the specified components and styling methods covered in the summary.

Requirements:

  1. Imports: Import all necessary components. You will need SafeAreaView, View, Text, TextInput, Pressable, and StyleSheet from react-native. You will also need Image from expo-image and useState from react.

  2. Component Structure:

    • The root element of your UserProfileCard component must be a SafeAreaView to avoid UI obstructions.
    • Inside the SafeAreaView, create a main container View that uses Flexbox to center its content both horizontally and vertically and has a background color of #f0f0f0.
  3. The Profile Card (View):

    • This View should be styled as a card: a white background, padding of 20, a borderRadius of 16, and an elevation of 5 for an Android shadow.
    • The card's items should be arranged vertically from top to bottom.
  4. Card Content:

    • Avatar: Use the Image component from expo-image. It should display the avatarUrl from the userData object. Style it to be 100x100 pixels with a borderRadius of 50 to make it circular. Give it a marginBottom of 12.
    • User Info: Use <Text> components to display the name and bio. The name should have a fontSize of 24 and be bold. The bio should have a fontSize of 16, a gray color, and be centered.
    • Input Field: Add a TextInput. It must be a controlled component tied to a state variable named comment. Style it with a borderWidth of 1, a borderColor of #cccccc, a borderRadius of 8, padding of 10, and a marginTop of 20.
    • Action Button: Create a Pressable component to act as a "Follow" button. It should not be the basic <Button>. Inside the Pressable, place a <Text> component with the word "Follow". Style the Pressable to have a backgroundColor of #007bff, padding of 12, a borderRadius of 8, and a marginTop of 16. The text inside should be white and bold.

Expected result

The output should be a single, vertically and horizontally centered card against a light grey background. The card itself is white with rounded corners and a visible shadow.

Inside the card, arranged from top to bottom, you should see:

  1. A circular image (the user's avatar).
  2. The user's name, "Jane Doe", in a large, bold font.
  3. The user's bio, "React Native Developer | Expo Enthusiast", in a smaller, grey font.
  4. A text input box with a light grey border and rounded corners.
  5. A blue button with rounded corners containing the word "Follow" in white, bold text.

The entire component should be contained within the safe area of the screen, not hidden by any device notches or status bars.

javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.