react-localization
react-localization copied to clipboard
global instance / global language
How do I integrate the script so that I only have one instance and all placeholders are replaced if i call setLanguage()?
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
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 :)