React: Translations from context

The interface's language is needed everywhere. Provide it, with a translation function, through context.

What to build

A page that switches between English and French using a translation context.

Requirements

  • Keep the language (en to start) in state in App and provide { language, setLanguage, t } through LanguageContext.
  • t(key, values) returns the text for the key in the current language, replacing {name} style placeholders with the values; a key missing in French uses the English text, and an unknown key returns the key itself.
  • Texts: title (Welcome / Bienvenue), items (You have {count} items / Vous avez {count} articles), help (English only: Need help?). Render an h1 with title, a p with the id items with items for count 3, a p with the id help with help, and a p with the id missing with the key nothing.
  • A select with the id language and the options en and fr switches the language.

Constraints

Components read the texts through useContext.

Example

In French the page shows "Bienvenue", "Vous avez 3 articles", "Need help?" (no French text) and "nothing".

Why it works

The provider owns the language and the lookup, so every component translates the same way, and switching the select renders every reader in the new language at once.

Hints

Hint 1

Provide { language, setLanguage, t }, where t(key, values) looks the key up in the current language and fills in {name} placeholders.

Hint 2

If a key is missing in the current language, fall back to English, and then to the key itself.

Solution

Show one correct solution (try it yourself first)
import { createContext, useContext, useState } from "react";

const TEXTS = {
  en: { title: "Welcome", items: "You have {count} items", help: "Need help?" },
  fr: { title: "Bienvenue", items: "Vous avez {count} articles" },
};

const LanguageContext = createContext(null);

function useT() {
  return useContext(LanguageContext).t;
}

function Page() {
  const t = useT();
  return (
    <div>
      <h1>{t("title")}</h1>
      <p id="items">{t("items", { count: 3 })}</p>
      <p id="help">{t("help")}</p>
      <p id="missing">{t("nothing")}</p>
    </div>
  );
}

function LanguagePicker() {
  const { language, setLanguage } = useContext(LanguageContext);
  return (
    <select id="language" value={language} onChange={(e) => setLanguage(e.target.value)}>
      <option value="en">en</option>
      <option value="fr">fr</option>
    </select>
  );
}

export default function App() {
  const [language, setLanguage] = useState("en");

  function t(key, values = {}) {
    const text = TEXTS[language][key] ?? TEXTS.en[key] ?? key;
    return text.replace(/\{(\w+)\}/g, (_, name) => String(values[name] ?? ""));
  }

  return (
    <LanguageContext value={{ language, setLanguage, t }}>
      <LanguagePicker />
      <Page />
    </LanguageContext>
  );
}

Lesson: Context: sharing values across the tree →