stefalda / ReactNativeLocalization

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

Do you need a state variable to trigger a "language changed" check? #206

Closed Frenzoid closed 2 years ago

Frenzoid commented 2 years ago

Hello, first of all, awesome library!, yet i think it lacks more examples, specificaly using the api and connecting with React.

Im trying to add a functionalitiy which would allow the users to change language, without the need to refresh the page, currently im doing it this way:

My locale.js file

import LocalizedStrings from 'react-localization';

export default new LocalizedStrings({
    en: {
        navbarItem1: "EN",

    },
    ch: {
        navbarItem1: "CH",
    }
});

My App.js file


....

// Resources
import locale from './locale/locale.js';

function App() {

  ....

  useEffect(() => {
    locale.setLanguage(localStorage.getItem("locale") || locale.getInterfaceLanguage());
    localStorage.setItem("locale", locale.getLanguage())
    console.log("Current Language:", locale.getLanguage());
  });

  let changeLocale = (language) => {
    locale.setLanguage(language);
    localStorage.setItem("locale", locale.getLanguage());
    console.log("Locale changed to:", language)
    window.location.reload();
  }

  ....

  }

So basically, the first time they join, the page will be translated to the native language, yet if they wish to change language, i have to store said change to the local storage, refresh the page, and grab the language from the local storage instead of the native one.

Is there any way to link these changes to React state, and have it change live, without the need to force a page refresh? If so, can i have a quick example please?

Best regards!

stefalda commented 2 years ago

Hi, you can use setState to refresh the interface. Have you tried?

Frenzoid commented 2 years ago

I see, so there must be a state variable to force the update check, i recommend you specify that on the readme.

Best regards.