react-localization icon indicating copy to clipboard operation
react-localization copied to clipboard

global instance / global language

Open gruessung opened this issue 6 years ago • 2 comments

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

gruessung avatar May 19 '18 14:05 gruessung

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

rockiger avatar Apr 20 '20 12:04 rockiger

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 :)

MarcARoberge avatar Aug 20 '20 01:08 MarcARoberge