I have a react native application in which the default language is English. I have a profile page in which the user can change the language from English to another language. And when the user saves the language change, the language including the title, drawer navigation names all should be changed to the user chosen language. How we can implement this functionality in react native?
Using a handler method called setLanguage , you can allow the functionality to switch between different languages from the LANGUAGES array defined above this function component. This function component uses Pressable from React Native to change the language.
To get the localized text onto the app, we need to call the i18n. t() function, and pass in the key we want to translate as a string. This gives us the value of the welcome key in our configuration object we imported based on the locale of the user's device. Welcome key of device set to English.
You can use this package: https://github.com/AlexanderZaytsev/react-native-i18n
Once installed all you have to do is to define your locale files, for example:
// src/i18n/locales/en.js
export default {
greeting: 'Hi!'
};
// src/i18n/locales/es.js
export default {
greeting: 'Hola!'
};
// src/i18n/locales/jp.js
export default {
greeting: 'Konichiwa!'
};
Then import those files and setup the configuration for i18n support like this:
// src/i18n/index.js
import I18n from 'react-native-i18n';
import en from './locales/en';
import es from './locales/es';
import jp from './locales/jp';
I18n.fallbacks = true;
I18n.translations = {
en,
es,
jp,
};
export default I18n;
And finally use it in your components like this:
import I18n from 'src/i18n';
class Demo extends React.Component {
render () {
return (
<Text>{I18n.t('greeting')}</Text>
)
}
}
By default it will use the device's locale, but if you want to overwrite that. For example when the user has device with a Spanish locale, but want to use Japanese, you can do something like this:
I18n.locale = 'jp';
Whenever you call I18n.t('greeting')
it will render Konichiwa!
. From now on, you will always need to use I18n.t
to render any text in your app.
The main issue with this library is the fact that you don't know which keys are still in use once your app grows, managing all your translations is super challenging, I'd recommend you to use a tool like LinguiJS for that: https://bleext.com/post/translating-your-product-into-multiple-languages
you can install i18n package from this link : https://github.com/AlexanderZaytsev/react-native-i18n
Now, in every part you need to make changes in your language just import I18n to js file:
import I18n from "react-native-i18n";
and use bottom code in onpress button
I18n.locale = "en"; // Language desired
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With