Multi language support in React Native apps
Jonas Grรธndahl
Posted on April 20, 2020
Hello everyone,
I had a look over at the following article to learn about how to create a multi language app in React Native:
https://medium.com/better-programming/creating-a-multi-language-app-in-react-native-9828b138c274
I thought to myself, there must be an easier way to do this. Let's make a Context provider and wrap the app inside of it:
import React, {useEffect, useState, useContext} from 'react';
import * as RNLocalize from 'react-native-localize';
const LanguageContext = React.createContext<>();
const translationGetters = {
en: () => require('../lang/translations/en.json'),
dk: () => require('../lang/translations/dk.json'),
};
export const LanguageProvider: React.FC = ({children}) => {
const [language, setLanguage] = useState('en');
useEffect(() => {
const fallback = {languageTag: 'en', isRTL: false};
const {languageTag} = RNLocalize.findBestAvailableLanguage(Object.keys(translationGetters)) ||
fallback;
setLanguage(languageTag);
}, []);
const value = {
...translationGetters[language](),
};
return (
<LanguageContext.Provider value={value}>
{children}
</LanguageContext.Provider>
);
};
export const useTranslation = () => useContext(LanguageContext);
In the above code, I'm using the react-native-localize
to grab the language of the device and then use to access the right language key inside my getter function. Now every component can call useTranslation() and grab the text they need.
Question is though if the above code is capable of doing the same as the code in the link. I'm not using a memoize function but really I'm just outputting text so is it really needed?
Hope somebody can shed some light on this! And if not, hopefully the code above is helpful in your next React Native app that needs multi language support ๐
Posted on April 20, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.