Cours React Native · Module 1: Ta première application

ScrollView et SafeAreaView

5 min de lecture ·
Dans cette leçon4

Quand le contenu ne tient pas à l'écran, il nous faut du défilement. Et SafeAreaView protège de l'encoche et des coins arrondis !

SafeAreaView - Marges sûres

Les téléphones modernes ont des encoches, des îlots dynamiques et des coins arrondis. SafeAreaView ajoute automatiquement des marges appropriées :

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}>Zone sûre</Text>
        <Text style={styles.description}>
          Ce texte ne sera pas coupé par l'encoche ou les coins arrondis !
        </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,
  },
});

Meilleure 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';

// À utiliser dans le fichier principal app/_layout.tsx
function RootLayout() {
  return (
    <SafeAreaProvider>
      <App />
    </SafeAreaProvider>
  );
}

// Dans les composants
function MyScreen() {
  const insets = useSafeAreaInsets(); // Accès aux valeurs de marge

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

ScrollView - Contenu défilant

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

export default function ScrollViewExample() {
  const treasures = [
    { id: 1, name: 'Diamant de Poséidon', rarity: 'Légendaire' },
    { id: 2, name: 'Trident de Pouvoir', rarity: 'Épique' },
    { id: 3, name: 'Coquillage de la Sagesse', rarity: 'Rare' },
    { id: 4, name: 'Ancre du Géant', rarity: 'Commun' },
    { id: 5, name: 'Clé des Portes', rarity: 'Épique' },
    { id: 6, name: 'Parchemin Ancien', rarity: 'Rare' },
    { id: 7, name: 'Amphore des Dieux', rarity: 'Légendaire' },
    { id: 8, name: 'Pièce d\'Or', rarity: 'Commun' },
    { id: 9, name: 'Gemme du Kraken', rarity: 'Légendaire' },
    { id: 10, name: 'Essence de l\'Océan', rarity: 'Épique' },
  ];

  return (
    <SafeAreaView style={styles.container}>
      <Text style={styles.header}>Trésors de l'Atlantide</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 === 'Légendaire' && styles.legendary,
              treasure.rarity === 'Épique' && 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 - Défilement horizontal

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

export default function HorizontalScrollExample() {
  const locations = [
    { id: 1, name: 'Palais de Poséidon', image: 'https://picsum.photos/200/150?random=1' },
    { id: 2, name: 'Temple des Profondeurs', image: 'https://picsum.photos/200/150?random=2' },
    { id: 3, name: 'Grotte du Kraken', image: 'https://picsum.photos/200/150?random=3' },
    { id: 4, name: 'Jardins de Corail', image: 'https://picsum.photos/200/150?random=4' },
    { id: 5, name: 'Épave du Titanic', image: 'https://picsum.photos/200/150?random=5' },
  ];

  return (
    <SafeAreaView style={styles.container}>
      <Text style={styles.header}>Découvre les lieux</Text>

      <ScrollView
        horizontal={true}
        showsHorizontalScrollIndicator={false}
        contentContainerStyle={styles.horizontalScroll}
        snapToInterval={220} // Aligner sur les cartes
        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 - Tirer pour rafraîchir

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('Dernière mise à jour : jamais');

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

    // Simuler la récupération de données
    setTimeout(() => {
      setData(`Dernière mise à jour : ${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}>
          Tire vers le bas pour rafraîchir
        </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',
  },
});

Entrées de la documentation utilisées dans cette leçon

Tu as repéré une erreur dans cette leçon ?

Teste tes connaissances

Réponds aux questions de cette leçon. Choisis une réponse pour voir tout de suite si elle est correcte.

  1. 1. À quoi sert SafeAreaView ?

  2. 2. Quelle prop active le défilement horizontal dans ScrollView ?

  3. 3. Quel composant utilise-t-on pour implémenter le « pull to refresh » dans ScrollView ?

  1. QuestionQuiz : SafeAreaView
  2. QuestionQuiz : ScrollView horizontal
  3. QuestionQuiz : Tirer pour rafraîchir

Articles utiles