Translation
The translation is one of the chores that must be included in every application, even if you're not planning to use multiple languages. Still, it allows you to manage your app's content from one place, a translation JSON file.
In addition, it allows you to easily add a second language whenever you decide to add it.
We highly recommend every developer use a translation mechanism from the start of the project.
In our template, we used the library i18next
+ react-i18next
, a fantastic combination of libraries to handle different translation cases in your app.
How to use translation:
Using translation, it's easy. But first, we must import the translate function and pass the key to the content we want to display.
Example:
import {useTranslation} from 'react-i18next';
[....]
const {t} = useTranslation();
[....]
<Description>{t('txt_welcome_to_rn_by_nh')}</Description>
If you want to switch the language, you can easily do it by running the following function:
const {i18n} = useTranslation();
function changeLanguage(){
i18n
.changeLanguage(i18n.language === 'ar' ? 'en' : 'ar')
.then(async () => {
await I18nManager.forceRTL(i18n.dir() === 'rtl');
})
.then(() => RNRestart.Restart())
}
You will notice that we restart the application after changing the language because react-native doesn't flip the UI automatically after changing the language using I18nManager
. But if you're using languages written in the same direction, feel free to remove the restart
function.