Translate with a Language Context

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code

Translate an app with a language context. Export a LanguageProvider component with props messages, initialLanguage ("en" when left out) and children, and a useTranslation hook that returns an object { language, setLanguage, t }. messages maps each language code to its messages, for example { en: { greeting: "Hello" }, fr: { greeting: "Bonjour" } }. t(key, values) returns the message for key in the current language; if that language doesn't have it, the English ("en") one; and if neither has it, the key itself. values is optional: each placeholder in curly braces, such as {name}, is replaced by the matching entry in values, so t("welcome", { name: "Ada" }) turns "Welcome, {name}!" into "Welcome, Ada!". setLanguage(code) switches the language for every component inside the provider. The default export App is a page with language buttons for the preview; the checks only use LanguageProvider and useTranslation.

Your code must pass

  • t looks messages up in the starting language
  • setLanguage switches every component
  • Falls back to English, then to the key
  • Fills in placeholders like {name}