React Native course ยท Module 1: Your first app

ScrollView and SafeAreaView

4 min read ยท
In this lesson4

When content doesn't fit on the screen, we need scrolling. And SafeAreaView protects against the notch and rounded corners!

SafeAreaView - Safe Margins

Modern phones have notches, dynamic islands, and rounded corners. SafeAreaView automatically adds appropriate margins:

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

export default function SafeAreaExample() {
  return (
    <SafeAreaView style={styles.safeArea}>
      <View style={styles.content}>
        <Text style={styles.title}>Safe Zone</Text>
        <Text style={styles.description}>
          This text will not be clipped by the notch or rounded corners!
        </Text>
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: '#1a5276',
  },
  content: {
    flex: 1,
    padding: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#fff',
  },
  description: {
    fontSize: 16,
    color: '#aed6f1',
    marginTop: 10,
  },
});

Better Solution: expo-safe-area-context

npx expo install react-native-safe-area-context
import { View, Text, StyleSheet } from 'react-native';
import { SafeAreaProvider, SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';

// Use in the main file app/_layout.tsx
function RootLayout() {
  return (
    <SafeAreaProvider>
      <App />
    </SafeAreaProvider>
  );
}

// In components
function MyScreen() {
  const insets = useSafeAreaInsets(); // Access to margin values

  return (
    <SafeAreaView style={styles.container} edges={['top', 'bottom']}>
      <Text>Top inset: {insets.top}px</Text>
      <Text>Bottom inset: {insets.bottom}px</Text>
    </SafeAreaView>
  );
}

ScrollView - Scrolling Content

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

export default function ScrollViewExample() {
  const treasures = [
    { id: 1, name: 'Poseidon\'s Diamond', rarity: 'Legendary' },
    { id: 2, name: 'Trident of Power', rarity: 'Epic' },
    { id: 3, name: 'Shell of Wisdom', rarity: 'Rare' },
    { id: 4, name: 'Giant\'s Anchor', rarity: 'Common' },
    { id: 5, name: 'Key to the Gates', rarity: 'Epic' },
    { id: 6, name: 'Ancient Scroll', rarity: 'Rare' },
    { id: 7, name: 'Amphora of the Gods', rarity: 'Legendary' },
    { id: 8, name: 'Gold Coin', rarity: 'Common' },
    { id: 9, name: 'Kraken\'s Gem', rarity: 'Legendary' },
    { id: 10, name: 'Ocean Essence', rarity: 'Epic' },
  ];

  return (
    <SafeAreaView style={styles.container}>
      <Text style={styles.header}>Treasures of Atlantis</Text>

      <ScrollView
        style={styles.scrollView}
        contentContainerStyle={styles.scrollContent}
        showsVerticalScrollIndicator={true}
      >
        {treasures.map((treasure) => (
          <View key={treasure.id} style={styles.card}>
            <Text style={styles.treasureName}>{treasure.name}</Text>
            <Text style={[
              styles.rarity,
              treasure.rarity === 'Legendary' && styles.legendary,
              treasure.rarity === 'Epic' && styles.epic,
              treasure.rarity === 'Rare' && styles.rare,
            ]}>
              {treasure.rarity}
            </Text>
          </View>
        ))}
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#1a5276',
  },
  header: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#fff',
    textAlign: 'center',
    paddingVertical: 16,
  },
  scrollView: {
    flex: 1,
  },
  scrollContent: {
    padding: 16,
    gap: 12,
  },
  card: {
    backgroundColor: '#2c3e50',
    borderRadius: 12,
    padding: 16,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  treasureName: {
    fontSize: 16,
    color: '#fff',
    fontWeight: '500',
  },
  rarity: {
    fontSize: 12,
    color: '#95a5a6',
    fontWeight: '600',
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 4,
    overflow: 'hidden',
  },
  legendary: {
    backgroundColor: '#f39c12',
    color: '#fff',
  },
  epic: {
    backgroundColor: '#9b59b6',
    color: '#fff',
  },
  rare: {
    backgroundColor: '#3498db',
    color: '#fff',
  },
});

ScrollView - Horizontal Scrolling

import { SafeAreaView, ScrollView, View, Text, Image, StyleSheet } from 'react-native';

export default function HorizontalScrollExample() {
  const locations = [
    { id: 1, name: 'Poseidon\'s Palace', image: 'https://picsum.photos/200/150?random=1' },
    { id: 2, name: 'Temple of the Depths', image: 'https://picsum.photos/200/150?random=2' },
    { id: 3, name: 'Kraken\'s Grotto', image: 'https://picsum.photos/200/150?random=3' },
    { id: 4, name: 'Coral Gardens', image: 'https://picsum.photos/200/150?random=4' },
    { id: 5, name: 'Titanic Wreck', image: 'https://picsum.photos/200/150?random=5' },
  ];

  return (
    <SafeAreaView style={styles.container}>
      <Text style={styles.header}>Discover Locations</Text>

      <ScrollView
        horizontal={true}
        showsHorizontalScrollIndicator={false}
        contentContainerStyle={styles.horizontalScroll}
        snapToInterval={220} // Snap to cards
        decelerationRate="fast"
      >
        {locations.map((location) => (
          <View key={location.id} style={styles.locationCard}>
            <Image
              source={{ uri: location.image }}
              style={styles.locationImage}
            />
            <Text style={styles.locationName}>{location.name}</Text>
          </View>
        ))}
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#1a5276',
  },
  header: {
    fontSize: 20,
    fontWeight: 'bold',
    color: '#fff',
    padding: 16,
  },
  horizontalScroll: {
    paddingHorizontal: 16,
    gap: 16,
  },
  locationCard: {
    width: 200,
    backgroundColor: '#2c3e50',
    borderRadius: 12,
    overflow: 'hidden',
  },
  locationImage: {
    width: '100%',
    height: 120,
  },
  locationName: {
    fontSize: 14,
    fontWeight: '600',
    color: '#fff',
    padding: 12,
    textAlign: 'center',
  },
});

RefreshControl - Pull to Refresh

import { SafeAreaView, ScrollView, Text, StyleSheet, RefreshControl } from 'react-native';
import { useState, useCallback } from 'react';

export default function RefreshExample() {
  const [refreshing, setRefreshing] = useState(false);
  const [data, setData] = useState('Last update: never');

  const onRefresh = useCallback(() => {
    setRefreshing(true);

    // Simulate data fetching
    setTimeout(() => {
      setData(`Last update: ${new Date().toLocaleTimeString()}`);
      setRefreshing(false);
    }, 2000);
  }, []);

  return (
    <SafeAreaView style={styles.container}>
      <ScrollView
        contentContainerStyle={styles.scrollContent}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={onRefresh}
            colors={['#3498db']} // Android
            tintColor="#3498db" // iOS
          />
        }
      >
        <Text style={styles.instruction}>
          Pull down to refresh
        </Text>
        <Text style={styles.data}>{data}</Text>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#1a5276',
  },
  scrollContent: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  instruction: {
    fontSize: 16,
    color: '#bdc3c7',
    marginBottom: 20,
  },
  data: {
    fontSize: 18,
    color: '#fff',
    fontWeight: '600',
  },
});

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What is SafeAreaView used for?

  2. 2. Which prop enables horizontal scrolling in ScrollView?

  3. 3. Which component do we use to implement 'pull to refresh' in ScrollView?

  1. QuestionQuiz: SafeAreaView
  2. QuestionQuiz: Horizontal ScrollView
  3. QuestionQuiz: Pull to refresh

Useful articles