Localization is essential for making your React Native app accessible to a global audience. By supporting multiple languages, you ensure users from different regions have a seamless experience. Let’s start step by step.
Step 1: Install Required Libraries
npm install i18next react-i18next react-native-localize
Step 2: Create Translation Files
Store translations in JSON files for each language. For example:
en.json (English):
{
"welcome": "Welcome",
"greeting": "Hello, {{name}}!"
}
bn.json (Bangali):
{
"welcome": "স্বাগতম",
"greeting": "হ্যালো, {{name}}!"
}
Step 3: Initialize i18next
import i18n from 'i18next';
import en from './locale-json/en.json';
import bn from './locale-json/bn.json';
import { initReactI18next } from 'react-i18next';
import { getLocales } from 'react-native-localize';
// Define the type for supported languages
export type TranslationKeys = keyof typeof en;
// Detect the device language
const getDeviceLanguage = (): string => {
const locales = getLocales();
return locales[0]?.languageTag || 'en';
};
// Initialize i18next
i18n.use(initReactI18next).init({
compatibilityJSON: 'v4',
resources: {
en: { translation: en },
bn: { translation: bn },
},
lng: getDeviceLanguage(),
fallbackLng: 'en',
interpolation: {
escapeValue: false,
},
});
export const i18nLocale = i18n;
Step 4: Wrap your app.js with the provider
import { I18nextProvider } from 'react-i18next';
import i18n from 'i18next';
const App = () => {
return (
<Provider store={store}>
<PaperProvider>
<I18nextProvider i18n={i18n}>
<SafeAreaProvider>
<Navigation />
</SafeAreaProvider>
</I18nextProvider>
</PaperProvider>
</Provider>
);
};
Step 5: Make a hook to make it more useful
import { useMemo } from 'react';
import { i18nLocale } from '../locale/i18nLocale.ts';
import { AppString } from '../locale/AppString.ts';
type AppStringKey = keyof typeof AppString; // Keys of APP_STRING
export const useLocalization = () => {
return useMemo(() => {
const localizedStrings: Record<AppStringKey, string> = {} as Record<
AppStringKey,
string
>;
(Object.keys(AppString) as AppStringKey[]).forEach((key) => {
localizedStrings[key] = i18nLocale.t(AppString[key]);
});
return localizedStrings;
}, []);
};
export const AppString = {
WELCOME: 'Welcome',
GEETINGS: "Hello, {{name}}!"
}
Step 6: Use it in your component
const App = () => {
const localization = useLocalization();
return (
<View>
<Text>{localization.WELCOME}</Text>
</View>
);
};
export default App;
Ref:
GitHub: https://github.com/piashcse/react-native-movie
Medium: https://piashcse.medium.com/localization-in-react-native-a2a48e45cd27
Very simple and clear guide to have a brief idea of the implementation, good job!
ReplyDelete