Par coderoe · 5 min de lecture

Dans ce tutoriel, nous allons configurer un système de traduction multilingue dans une application Expo React Native, en utilisant expo-localization pour détecter automatiquement la langue du système et gérer les traductions.
Installe toutes les dépendances nécessaires pour le système de traduction :
1# Détection automatique de la langue2npx expo install expo-localization3 4# Système de traduction5npm install i18next react-i18next6 7# Stockage persistant8npx expo install @react-native-async-storage/async-storage9 10# Icônes (optionnel)11npm install lucide-react-nativeCrée une structure de dossiers pour organiser tes traductions par langue :
1translation/2├── index.ts3└── locales/4 ├── fr-FR.json5 └── en-US.json1{2 "welcome": "Bonjour"3}1{2 "welcome": "Hello"3}Crée le fichier translation/index.ts avec la configuration complète utilisant i18next et react-i18next :
1import AsyncStorage from "@react-native-async-storage/async-storage";2import * as Localization from "expo-localization";3import i18n from "i18next";4import { initReactI18next } from "react-i18next";5 6import enUS from './locales/en-US.json';7import frFR from "./locales/fr-FR.json";8 9const resources = {10 "fr-FR": { translation: frFR },11 'en-US': { translation: enUS },12};13 14const initI18n = async () => {15 try {16 let savedLanguage = await AsyncStorage.getItem("language");17 18 if (!savedLanguage) {19 savedLanguage = Localization.getLocales()[0]?.languageTag || "en-US";20 }21 22 i18n.use(initReactI18next).init({23 resources,24 lng: savedLanguage,25 fallbackLng: "en-US",26 interpolation: {27 escapeValue: false,28 },29 });30 } catch (error) {31 console.error("Erreur lors de l'initialisation de i18n:", error);32 // Fallback en cas d'erreur33 i18n.use(initReactI18next).init({34 resources,35 lng: "en-US",36 fallbackLng: "en-US",37 interpolation: {38 escapeValue: false,39 },40 });41 }42};43 44initI18n();45 46export default i18n;Localization.getLocales()[0]?.languageTag détecte la langue du système au démarrageAsyncStorage sauvegarde le choix de langue de l'utilisateurCrée ton composant principal app/index.tsx :
1import { useState } from "react";2import { Text, View, TouchableOpacity, StyleSheet } from "react-native";3 4import AsyncStorage from "@react-native-async-storage/async-storage";5import { useTranslation } from "react-i18next";6import { Check } from "lucide-react-native";7 8import i18n from "@/translation";9 10export default function Index() {11 const { t } = useTranslation();12 const [currentLanguage, setCurrentLanguage] = useState(i18n.language);13 14 const languages = [15 { code: "en-US", name: "English" },16 { code: "fr-FR", name: "Français" },17 ];18 19 const changeLanguage = async (lng: string) => {20 try {21 await AsyncStorage.setItem("language", lng);22 i18n.changeLanguage(lng);23 setCurrentLanguage(lng);24 } catch (error) {25 console.error("Erreur lors de la sauvegarde de la langue:", error);26 }27 };28 29 return (30 <View style={styles.container}>31 <Text style={styles.text}>{t("welcome")}</Text>32 <View style={styles.containerButton}>33 {languages.map((lang) => (34 <TouchableOpacity35 key={lang.code}36 onPress={() => changeLanguage(lang.code)}37 style={styles.button}38 activeOpacity={0.8}39 >40 <Text style={styles.buttonText}>{lang.name}</Text>41 {currentLanguage === lang.code && <Check />}42 </TouchableOpacity>43 ))}44 </View>45 </View>46 );47}48 49const styles = StyleSheet.create({50 container: {51 flex: 1,52 justifyContent: "center",53 alignItems: "center",54 gap: 20,55 },56 text: {57 fontSize: 32,58 fontWeight: "bold",59 },60 containerButton: {61 width: "100%",62 gap: 1,63 },64 button: {65 height: 60,66 width: "100%",67 backgroundColor: "#fff",68 flexDirection: "row",69 alignItems: "center",70 justifyContent: "space-between",71 paddingHorizontal: 20,72 },73 buttonText: {74 fontSize: 20,75 fontWeight: "500",76 textAlign: "center",77 color: "#000",78 },79});const { t } = useTranslation() fournit la fonction de traductioncurrentLanguage force le re-render quand la langue changet("welcome") retourne "Bonjour" en français ou "Hello" en anglaisAsyncStorage sauvegarde le choix de langueLance ton projet avec :
1npx expo startPour ajouter de nouvelles traductions, ajoute simplement de nouvelles clés dans tes fichiers JSON :
translation/locales/fr-FR.json :
1{2 "welcome": "Bonjour",3 "hello": "Salut",4 "myNewKey": "Ma nouvelle traduction"5}translation/locales/en-US.json :
1{2 "welcome": "Hello",3 "hello": "Hi",4 "myNewKey": "My new translation"5}Puis utilise-la dans ton code :
1<Text>{t("myNewKey")}</Text>translation/locales/es-ES.json pour l'espagnoltranslation/index.ts :1import esES from './locales/es-ES.json';2 3const resources = {4 "fr-FR": { translation: frFR },5 'en-US': { translation: enUS },6 'es-ES': { translation: esES },7};1const languages = [2 { code: "en-US", name: "English" },3 { code: "fr-FR", name: "Français" },4 { code: "es-ES", name: "Español" },5];C'est tout ! Tu as maintenant un système de traduction complet et type-safe pour ton application Expo.

Par coderoe · 5 min de lecture

Par coderoe · 5 min de lecture

Par coderoe · 8 min de lecture