Wk-notes-03-16-i18n-solution

i18n Solution

Solution

Provider provides intl dictionary, Consumer takes the intl and translate() it with hardcoded (nested)id, and fallback,

Pluralise and templating:

In dictionary, each fields supports plural

// Dictionary:
"passengers": { 
  "none":"No passengers", 
  "one":"One passenger", 
  "many":"{{count}} passengers"
}

// Component:
<Text id="passengers" plural={0} /> // "No passengers"
<Text id="passengers" plural={1} /> // "One passenger"
<Text id="passengers" plural={2} fields={{ count: 2 }} /> // "2 passengers"

// HOC 
withIntl((t) => {
    return t('passengers', "fallback", { plural:2 })
})

Basic function

Context

createContext({ dictionary: null, highlight: false });

Provider:

<IntlContext.Provider value={{ highlight, dictionary }}>{children}</IntlContext.Provider>

Consumer:

<IntlContext.Consumer>(intl) => {children}</IntlContext.Consumer>

or

useContext(IntlContext)

Detail in consumer:

  • Dealing with hightlight

  • Expose just enough api

  • call translate()

translate() from intl

return translated string.

Last updated

Was this helpful?