stefalda / ReactNativeLocalization

Class to localize the ReactNative interface
MIT License
898 stars 123 forks source link

Support multiple bundles and dependency injection? #192

Closed Winglonelion closed 3 years ago

Winglonelion commented 3 years ago

Hello, react-native-localization is a very good library and very stable. It included in many applications of me.

But by the time bind with the library. I found an issue with this way to implement multiple languages using react-native-localization

It's redundant of keys in the string bundle when application messages updated. Some times, some view removed and it's very hard to check that is that this key still used in bundle.

So I think multiple bundles with dependency injection is a good solution to manage the keys in the project.

The implementation way could be like that

import LocalizedStrings from 'react-native-localization';

// -- folder Home -> messages.js
const bundleHome = new LocalizedStrings({
  en: {...}
  fr: {...}
})

LocalizedStrings.inject(bundleHome)

// -- folder Home -> View.jsx
<Text>{bundleHome.title}</Text>

// -- folder Cart -> messages.js

const bundleCart = new LocalizedStrings({
  en: {...}
  fr: {...}

LocalizedStrings.inject(bundleCart)

// -- folder Cart -> View.jsx
<Text>{bundleCart.title}</Text>

// -- for change language
LocalizedStrings.setLanguage('fr')

So, the messages of module managed by own module. When removing the module, the messages also be removed.

Winglonelion commented 3 years ago

@stefalda st Please take a look

stefalda commented 3 years ago

Hi @Winglonelion, you could have multiple instances of LocalizedString one for each view and then dispatch somehow a language change.

Your proposal is to add a new method to integrate further strings in the same LocalizedString object... is it right?

Stefano

Winglonelion commented 3 years ago

Hi @Winglonelion, you could have multiple instances of LocalizedString one for each view and then dispatch somehow a language change.

Your proposal is to add a new method to integrate further strings in the same LocalizedString object... is it right?

Stefano

@stefalda st Thanks for quick feedback, I'm not sure for multiple instance strings. It not yet included in doc. My target is a way to easily manage string keys in bundle. Which follows module design pattern and can easy to be add / remove in project. And your comment is really inspiring.

So we can create multiple LocalizedString instances. And then inject it into a manager. Once change language, just iterating over all instance call setLanguage

const stringBundlesSet = []

export const injectStringBundleSet = (strings: LocalizedString) => {
  stringBundlesSet.push(strings)
}

export const changeLanguage = (languageCode: String) => {
  stringBundlesSet.forEach(bundle => {
    bundle.setLanguage(languageCode)
})
}