stefalda / react-localization

Simple module to localize the React interface using the same syntax used in the ReactNativeLocalization module.
MIT License
372 stars 57 forks source link

global instance / global language #75

Open gruessung opened 6 years ago

gruessung commented 6 years ago

How do I integrate the script so that I only have one instance and all placeholders are replaced if i call setLanguage()?

rockiger commented 4 years ago

I use a React Context like so:

import React, { createContext, useContext, useMemo } from 'react'
import LocalizedStrings from 'react-localization'

export { TranslationProvider, useTranslation }

const TranslationContext = createContext()

function useTranslation () {
  const context = useContext(TranslationContext)
  if (!context) {
    throw new Error('useTranslation must be used within a TranslationProvider')
  }
  return context
  // t.setLanguage('de') if we want to create a language switch later
}

function TranslationProvider ({ translations, ...props }) {
  console.log(translations)
  let t
  if (translations) {
    t = new LocalizedStrings(translations)
  }
  const value = useMemo(() => t, [t])
  return <TranslationContext.Provider value={value} {...props} />
}

Then wrap around the components you need the translations:

import { TranslationProvider } from 'src/components/Translations/Translations'
...

        <TranslationProvider translations={translations}>
            ...
        </TranslationProvider>

Finally access the translation in the components with the 'useTranslation` hook:

import { useTranslation } from 'src/components/Translations/Translations'
...
{t.name}
...

Hope this helps

MarcARoberge commented 4 years ago

I tried to implement this solution, but when I change the language, it does not re-render the app.

Edit: Since I am using Redux, I used an action to modify the language and by returning the same store as a new object { ...store }, it triggers a re-render. Let me know if you have a better way to do this :)