React Native Localize Helper 🌍

A simple, lightweight, and easy-to-use helper library for handling localization (i18n) in your React Native applications. Designed with simplicity for developers of all levels.
✨ Features
- ✅ Easy Initialization: Set up translations with minimal configuration.
- ✅ Simple Translation Function: Use the intuitive
t()
function for key-based translation.
- ✅ React Hook: Seamlessly integrate with functional components using the
useTranslation()
hook.
- ✅ Placeholder Support: Easily replace dynamic values within translations (e.g.,
Welcome, {{name}}!
).
- ✅ Language Switching: Dynamically change the active language.
- ✅ Fallback Language: Automatically falls back to a default language if a translation key is missing.
- ✅ TypeScript Support: Written in TypeScript with included type definitions.
🚀 Installation
Choose your preferred package manager:
npm install react-native-localize-helper
yarn add react-native-localize-helper
📖 Usage GuideFollow these steps to integrate react-native-localize-helper into your app:1. Prepare Your Translation ResourcesCreate files to store your translations. You can structure this however you like, but a common approach is to have a central file that exports all resources, potentially importing from individual language files (JS objects or JSON).Example: src/translations/index.ts (or .js)// src/translations/index.ts
import type { TranslationResources } from 'react-native-localize-helper';
export const resources: TranslationResources = {
// English
en: {
greeting: 'Hello!',
welcome: 'Welcome to the app, {{name}}!',
farewell: 'Goodbye',
screenTitle_home: 'Home',
button_changeLang: 'Change Language',
},
// Spanish
es: {
greeting: '¡Hola!',
welcome: '¡Bienvenido/a a la app, {{name}}!',
farewell: 'Adiós',
screenTitle_home: 'Inicio',
button_changeLang: 'Cambiar Idioma',
},
// French
fr: {
greeting: 'Bonjour !',
welcome: 'Bienvenue sur l\'application, {{name}} !',
// 'farewell' is missing, will fallback if 'en' is default
screenTitle_home: 'Accueil',
button_changeLang: 'Changer de Langue',
},
// Add more languages...
};
(Tip: For larger apps, consider splitting each language into its own file, e.g., en.json, es.json, and importing them into this main resources object.)2. Initialize the LibraryCall initLocalization once when your application starts, before rendering any components that need translations. Your main App.tsx or App.js is the ideal place.// App.tsx (or App.js)
import React from 'react';
import { initLocalization } from 'react-native-localize-helper';
import { resources } from './src/translations'; // Import your resources
import AppNavigation from './src/navigation/AppNavigation'; // Your app's main component/navigator
// --- Initialize Localization ---
initLocalization({
resources: resources, // Pass the translation data
defaultLanguage: 'en', // Fallback language (Required if initialLanguage isn't guaranteed to exist)
initialLanguage: 'en', // Optional: Set the starting language (e.g., detect from device)
});
// --- End Initialization ---
function App() {
return <AppNavigation />; // Or your main App component
}
export default App;
3. Use Translations in ComponentsImport the useTranslation hook within your functional components to access translation capabilities.// src/screens/HomeScreen.tsx
import React from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
import { useTranslation } from 'react-native-localize-helper';
const HomeScreen = () => {
// Get the t function, current language, and setter from the hook
const { t, currentLanguage, setLanguage } = useTranslation();
const handleLanguageChange = (lang: string) => {
setLanguage(lang); // Update the global language
};
return (
<View style={styles.container}>
{/* Use t() to translate keys */}
<Text style={styles.title}>{t('screenTitle_home')}</Text>
<Text style={styles.text}>{t('greeting')}</Text>
<Text style={styles.text}>{t('welcome', { name: 'User' })}</Text>
<Text style={styles.text}>{t('farewell')}</Text>
<Text style={styles.info}>Current Language: {currentLanguage}</Text>
{/* Language switching buttons */}
<View style={styles.buttonContainer}>
<Button title="English" onPress={() => handleLanguageChange('en')} disabled={currentLanguage === 'en'} />
<Button title="Español" onPress={() => handleLanguageChange('es')} disabled={currentLanguage === 'es'} />
<Button title="Français" onPress={() => handleLanguageChange('fr')} disabled={currentLanguage === 'fr'} />
</View>
</View>
);
};
// Add styles...
const styles = StyleSheet.create({
container: { flex: 1, alignItems: 'center', justifyContent: 'center', padding: 20 },
title: { fontSize: 22, fontWeight: 'bold', marginBottom: 15 },
text: { fontSize: 16, marginBottom: 8 },
info: { fontSize: 14, fontStyle: 'italic', marginTop: 20 },
buttonContainer: { flexDirection: 'row', justifyContent: 'space-around', width: '100%', marginTop: 25 },
});
export default HomeScreen;
4. Use t() Outside Components (Optional)If you need translations in utility functions or other non-component parts of your code (after initialization), you can import t directly:import { t } from 'react-native-localize-helper';
function getGreetingMessage() {
// Make sure initLocalization was called before this function runs
return t('greeting');
}
📚 API ReferenceinitLocalization(options: InitOptions)Initializes the library.options.resources: TranslationResources (Required) - The object containing all language translations.options.defaultLanguage: string (Optional, defaults to 'en') - The language code to use as a fallback when a key is missing in the currentLanguage.options.initialLanguage: string (Optional, defaults to defaultLanguage) - The language code to set as active when the app starts.t(key: string, options?: TranslationOptions): stringThe core translation function.key: string (Required) - The key identifying the string to translate.options: Record<string, string | number> (Optional) - An object containing key-value pairs for placeholder replacement (e.g., { name: 'User' } replaces {{name}}).Returns: The translated string for the currentLanguage, or the defaultLanguage string if the key is missing, or the key itself if not found in either.useTranslation(): UseTranslationResponseReact Hook for use in functional components.Returns: An object with:t: The translation function described above.currentLanguage: string - The currently active language code.setLanguage: (language: string) => void - A function to change the active language. Components using the hook will re-render automatically.setLanguage(language: string): voidGlobally sets the active language for all subsequent t() calls and updates components using useTranslation().language: string (Required) - The language code to switch to (must exist in the initialized resources).getCurrentLanguage(): stringSynchronously returns the currently active language code.🤝 ContributingContributions, issues, and feature requests are welcome! Feel free to check the issues page (replace with your actual repo link).📜 LicenseThis project is licensed under the MIT