0 XP
?
Développement Mobile React Native/Navigation avec React Navigation
Intermédiaire65 min45 XP

Objectifs de cette leçon

  • Installer et configurer React Navigation
  • Créer des écrans avec navigation
  • Passer des paramètres entre écrans

Navigation avec React Navigation 🧭

Dans une app mobile, on ne charge pas de nouvelles pages HTML ! On navigue entre des écrans. React Navigation est LA solution standard.


1. Stack Navigator : empiler les écrans 📚

tsx import { NavigationContainer } from "@react-navigation/native"; import { createNativeStackNavigator } from "@react-navigation/native-stack"; import { View, Text, TouchableOpacity, StyleSheet } from "react-native";

// 1. Définition des types type RootStackParamList = { Accueil: undefined; Profil: { userId: number; nom: string }; };

// 2. Création du Stack const Stack = createNativeStackNavigator<RootStackParamList>();

// 3. Écran Accueil function EcranAccueil({ navigation }: any) { return ( <View style={styles.container}> <Text style={styles.titre}>Bienvenue !</Text> <TouchableOpacity style={styles.bouton} onPress={() => navigation.navigate("Profil", { userId: 42, nom: "Alice", }) } > <Text style={styles.boutonTexte}>Voir le profil →</Text> </TouchableOpacity> </View> ); }

// 4. Écran Profil (reçoit les paramètres) function EcranProfil({ route, navigation }: any) { const { userId, nom } = route.params; return ( <View style={styles.container}> <Text style={styles.titre}>Profil #{userId}</Text> <Text style={styles.texte}>Nom : {nom}</Text> <TouchableOpacity style={[styles.bouton, { backgroundColor: "#666" }]} onPress={() => navigation.goBack()} > <Text style={styles.boutonTexte}>← Retour</Text> </TouchableOpacity> </View> ); }

// 5. App principale function AppNavigator() { return ( <NavigationContainer> <Stack.Navigator initialRouteName="Accueil"> <Stack.Screen name="Accueil" component={EcranAccueil} /> <Stack.Screen name="Profil" component={EcranProfil} /> </Stack.Navigator> </NavigationContainer> ); } ``'


2. Tab Navigator : onglets en bas 📊

import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";

const Tab = createBottomTabNavigator();

function AppTabs() {
  return (
    <Tab.Navigator
      screenOptions={{
        tabBarActiveTintColor: "#6200ee",
        tabBarInactiveTintColor: "#999",
        tabBarStyle: {
          backgroundColor: "#fff",
          borderTopWidth: 1,
          borderColor: "#eee",
          height: 60,
          paddingBottom: 8,
        },
      }}
    >
      <Tab.Screen
        name="Accueil"
        component={EcranAccueil}
        options={{ tabBarLabel: "Accueil", tabBarIcon: () => <Texte>🏠</Texte> }}
      />
      <Tab.Screen
        name="Recherche"
        component={EcranRecherche}
        options={{ tabBarLabel: "Recherche", tabBarIcon: () => <Texte>🔍</Texte> }}
      />
      <Tab.Screen
        name="Profil"
        component={EcranProfil}
        options={{ tabBarLabel: "Profil", tabBarIcon: () => <Texte>👤</Texte> }}
      />
    </Tab.Navigator>
  );
}
``'

---

## 3. Drawer Navigator : menu latéral 🗂️

tsx
import { createDrawerNavigator } from "@react-navigation/drawer";

const Drawer = createDrawerNavigator();

function AppDrawer() {
  return (
    <Drawer.Navigator screenOptions={{ headerShown: true }}>
      <Drawer.Screen name="Accueil" component={EcranAccueil} />
      <Drawer.Screen name="Profil" component={EcranProfil} />
      <Drawer.Screen name="Paramètres" component={EcranParametres} />
    </Drawer.Navigator>
  );
}
``'

---

## 4. Navigation imbriquée 🪆

```text
' On peut mélanger les navigators !
' Exemple : Tab Navigator en bas + Stack dans chaque onglet

' Structure :
'   TabNavigator
'     ├── StackAccueil
'     │     ├── Accueil
'     │     └── Détails
'     ├── StackRecherche
'     │     ├── Recherche
'     │     └── Résultats
'     └── StackProfil
'           ├── Profil
'           └── Paramètres
``'

---

## 5. Deep Linking 🔗

```tsx
// Deep linking = ouvrir l'app depuis un lien !
// Exemple : monapp://profil/42

const linking = {
  prefixes: ["monapp://", "https://monapp.com"],
  config: {
    screens: {
      Accueil: "accueil",
      Profil: "profil/:userId",  // :userId = paramètre dynamique
    },
  },
};

// Dans App.tsx
<NavigationContainer linking={linking}>
  <Stack.Navigator>...</Stack.Navigator>
</NavigationContainer>

// Maintenant, cliquer sur https://monapp.com/profil/42
// → Ouvre l'app directement sur l'écran Profil avec userId = 42 !
``'

---

## Exercices pour toi 🎯

1. **Stack + Tab** : crée 3 onglets (Accueil, Recherche, Profil). Dans l'onglet Accueil, un Stack avec une page de détails
2. **Passage de paramètres** : l'écran liste affiche des articles, cliquer sur un article navigue vers Détails avec les infos de l'article
3. **Deep linking** : configure un lien `monapp://article/5` qui ouvre directement l'article 5

Création des variables pas à pas

Prêt à explorer la mémoire

Appuie sur Play pour voir les variables se créer une par une

0/5

Exécution pas à pas

0/6

Visualisation d'exécution

ligne 18
code
1import { NavigationContainer } from '@react-navigation/native';
2import { createNativeStackNavigator } from '@react-navigation/native-stack';
3
4const Stack = createNativeStackNavigator();
5
6function Accueil({ navigation }: any) {
7 return <Text onPress={() => navigation.navigate('Profil', { id: 1 })}>Voir profil</Text>;
8}
9
10function Profil({ route }: any) {
11 return <Text>Profil {route.params.id}</Text>;
12}
13
14export default function App() {
15 return (
16 <NavigationContainer>
17 <Stack.Navigator initialRouteName="Accueil">
18 <Stack.Screen name="Accueil" component={Accueil} />
19 <Stack.Screen name="Profil" component={Profil} />
20 </Stack.Navigator>
21 </NavigationContainer>
22 );
23}
Variables
Stack.Navigator=pile d'écrans
navigation.navigate=('Profil', { id: 1 })
route.params={ id: 1 }

📚 Pile de navigation (Stack)

Accueil
#0
⬆ Push = ajouter au sommet | ⬇ Pop = enlever du sommet

⚡ Simulateur — Navigation React Native

Étape 1/7
📝 Pseudo-code
1// Configuration de la navigation
2import { NavigationContainer } from '@react-navigation/native';
3import { createNativeStackNavigator } from '@react-navigation/native-stack';
4
5const Stack = createNativeStackNavigator(); # ⬅ créer le stack
6
7function Accueil({ navigation }) {
8 return <Button title='Voir profil' onPress={() => # ⬅ naviguer
9 navigation.navigate('Profil', { id: 1 })} />;
10}
11
12function Profil({ route }) { # ⬅ recevoir params
13 return <Text>Profil {route.params.id}</Text>;
14}
15
16export default function App() {
17 return (
18 <NavigationContainer>
19 <Stack.Navigator initialRouteName='Accueil'> # ⬅ écran départ
20 <Stack.Screen name='Accueil' component={Accueil} /> # ⬅ déclarer
21 <Stack.Screen name='Profil' component={Profil} />
22 </Stack.Navigator>
23 </NavigationContainer>
24 );
25}
🗺️ Navigation
💡 Navigation
  • Stack : empile/dépile des écrans (push/pop)
  • Tab : onglets en bas de l'écran
  • Params : passage de données entre écrans

React Navigation est la solution de navigation la plus populaire pour React Native.