Kurs JavaScript i React · Moduł 10: Ekosystem i przyszłość React

React-i18next - Internacjonalizacja aplikacji React

14 min czytania ·
W tej lekcji11

Na pokład wchodzi załoga z całej galaktyki: kapitan czyta komunikaty po polsku, nawigatorka po angielsku, a inżynier po hiszpańsku. Jeśli teksty są wpisane na sztywno w JSX, każdy nowy język oznacza przepisywanie komponentów. Rozwiązaniem jest internacjonalizacja (i18n): komponent zna tylko klucze, a tłumaczenia leżą w osobnych plikach. React-i18next łączy z Reactem bibliotekę i18next, która formatuje też daty, liczby i waluty.

Instalacja i konfiguracja

Instalujesz rdzeń i18next, integrację react-i18next i dwie opcjonalne wtyczki: wykrywacz języka oraz backend HTTP:

npm install react-i18next i18next i18next-browser-languagedetector i18next-http-backend

Konfiguracja to łańcuch: każde use() podłącza wtyczkę, init() ustawia opcje, a na końcu eksportujesz instancję:

// i18n.js
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import Backend from 'i18next-http-backend';
import LanguageDetector from 'i18next-browser-languagedetector';

i18n
  .use(Backend) // Ładowanie tłumaczeń z serwera
  .use(LanguageDetector) // Automatyczne wykrywanie języka
  .use(initReactI18next) // Integracja z React
  .init({
    // Konfiguracja fallback
    fallbackLng: 'en',

    // Debugowanie w development
    debug: process.env.NODE_ENV === 'development',

    // Interpolacja
    interpolation: {
      escapeValue: false // React już zabezpiecza przed XSS
    },

    // Konfiguracja Backend
    backend: {
      loadPath: '/locales/{{lng}}/{{ns}}.json'
    },

    // Konfiguracja detectora języka
    detection: {
      order: ['localStorage', 'navigator', 'htmlTag'],
      caches: ['localStorage']
    }
  });

export default i18n;

fallbackLng: 'en' to język awaryjny, a escapeValue: false wyłącza podwójne escapowanie, bo React sam chroni przed XSS. W prostszym projekcie zamiast backendu podasz tłumaczenia wprost: init({ resources, lng }).

Konfigurację importujesz raz, w pliku startowym, przed renderowaniem aplikacji:

// index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './i18n'; // Import konfiguracji
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

Import tylko inicjalizuje i18next, więc App nie dostaje niczego przez propsy.

Hook useTranslation

W komponencie sięgasz po useTranslation. Hook zwraca funkcję t(), która zamienia klucz na tekst, i obiekt i18n z metodą changeLanguage:

// App.jsx
import { useTranslation } from 'react-i18next';

function App() {
  const { t, i18n } = useTranslation();

  const changeLanguage = (lang) => {
    i18n.changeLanguage(lang);
  };

  return (
    <div>
      <h1>{t('welcome.title')}</h1>
      <p>{t('welcome.description')}</p>

      <div>
        <button onClick={() => changeLanguage('en')}>English</button>
        <button onClick={() => changeLanguage('pl')}>Polski</button>
        <button onClick={() => changeLanguage('es')}>Español</button>
      </div>

      <p>{t('current_language')}: {i18n.language}</p>
    </div>
  );
}

export default App;

Klucz welcome.title wskazuje zagnieżdżone pole w JSON. Po changeLanguage('pl') każdy komponent z tym hookiem przerenderuje się z nowymi tekstami.

Pliki tłumaczeń mają identyczne klucze i różnią się tylko wartościami:

// public/locales/en/translation.json
{
  "welcome": {
    "title": "Welcome to our application",
    "description": "This is a multilingual React application"
  },
  "current_language": "Current language",
  "navigation": {
    "home": "Home",
    "about": "About",
    "contact": "Contact"
  }
}

// public/locales/pl/translation.json
{
  "welcome": {
    "title": "Witaj w naszej aplikacji",
    "description": "To jest wielojęzyczna aplikacja React"
  },
  "current_language": "Aktualny język",
  "navigation": {
    "home": "Strona główna",
    "about": "O nas",
    "contact": "Kontakt"
  }
}

Backend znajdzie je pod ścieżką /locales/{{lng}}/{{ns}}.json, gdzie lng to język, a ns przestrzeń nazw.

Interpolacja i pluralizacja

Dane, jak imię czy liczbę wiadomości, przekazujesz jako drugi argument funkcji t():

function UserProfile({ user, messageCount }) {
  const { t } = useTranslation();

  return (
    <div>
      {/* Interpolacja */}
      <h1>{t('user.greeting', { name: user.name })}</h1>

      {/* Pluralizacja */}
      <p>{t('messages.count', { count: messageCount })}</p>

      {/* Formatowanie dat */}
      <p>{t('user.joined', {
        date: new Date(user.joinedAt),
        formatParams: {
          date: { year: 'numeric', month: 'long', day: 'numeric' }
        }
      })}</p>
    </div>
  );
}

{{name}} w tłumaczeniu zostanie zastąpione wartością user.name. Przy liczbie mnogiej zmienna musi nazywać się dokładnie count. Datę formatuje zapis {{date, datetime}} w tłumaczeniu, a formatParams przekazuje mu opcje Intl.DateTimeFormat.

Formy liczby mnogiej rozróżniają przyrostki kluczy:

// Pliki tłumaczeń z pluralizacją
{
  "user": {
    "greeting": "Hello, {{name}}!",
    "joined": "Member since {{date, datetime}}"
  },
  "messages": {
    "count_zero": "No messages",
    "count_one": "1 message",
    "count_other": "{{count}} messages"
  }
}

Od wersji 21 i18next dobiera przyrostek przez Intl.PluralRules: angielski ma formy _one i _other, a _zero to dodatkowy wariant dla zera. Polski potrzebuje _one (1 wiadomość), _few (2 wiadomości), _many (5 wiadomości) i _other (ułamki). Komponent się nie zmienia, zmieniają się tylko pliki.

Przestrzenie nazw

Namespaces dzielą ogromny plik tłumaczeń na czytelne moduły, np. navigation, forms i errors:

// Konfiguracja z namespace
i18n.init({
  // Przestrzeń domyślna i lista wszystkich przestrzeni
  defaultNS: 'common',
  ns: ['common', 'navigation', 'forms', 'errors']
});

// Użycie różnych namespace
function Navigation() {
  const { t } = useTranslation('navigation');

  return (
    <nav>
      <a href="/">{t('home')}</a>
      <a href="/about">{t('about')}</a>
      <a href="/contact">{t('contact')}</a>
    </nav>
  );
}

function ContactForm() {
  const { t } = useTranslation(['forms', 'errors']);

  return (
    <form>
      <label>{t('forms:name.label')}</label>
      <input
        required
      />

      <label>{t('forms:email.label')}</label>
      <input
        type="email"
        required
      />

      <button type="submit">
        {t('forms:submit')}
      </button>
    </form>
  );
}

useTranslation('navigation') wybiera przestrzeń dla komponentu, a zapis forms:name.label sięga po klucz z konkretnej przestrzeni.

Kontekst języka

Przełącznik języka potrzebuje zwykle zapisu wyboru, listy języków i kierunku tekstu. Zbiera to LanguageProvider:

// LanguageContext.jsx
import { createContext, useContext, useState } from 'react';
import { useTranslation } from 'react-i18next';

const LanguageContext = createContext();

export function LanguageProvider({ children }) {
  const { i18n } = useTranslation();
  const [language, setLanguage] = useState(i18n.language);

  const changeLanguage = async (newLang) => {
    await i18n.changeLanguage(newLang);
    setLanguage(newLang);

    // Zapisz wybór w localStorage
    localStorage.setItem('preferredLanguage', newLang);

    // Zmień kierunek tekstu dla języków RTL
    if (['ar', 'he', 'fa'].includes(newLang)) {
      document.dir = 'rtl';
    } else {
      document.dir = 'ltr';
    }
  };

  const availableLanguages = [
    { code: 'en', name: 'English' },
    { code: 'pl', name: 'Polski' },
    { code: 'es', name: 'Español' },
    { code: 'fr', name: 'Français' },
    { code: 'de', name: 'Deutsch' }
  ];

  return (
    <LanguageContext.Provider value={{
      language,
      changeLanguage,
      availableLanguages,
      isRTL: ['ar', 'he', 'fa'].includes(language)
    }}>
      {children}
    </LanguageContext.Provider>
  );
}

export const useLanguage = () => {
  const context = useContext(LanguageContext);
  if (!context) {
    throw new Error('useLanguage must be used within LanguageProvider');
  }
  return context;
};

// LanguageSelector.jsx
function LanguageSelector() {
  const { language, changeLanguage, availableLanguages } = useLanguage();
  const { t } = useTranslation();

  return (
    <div className="language-selector">
      <select
        value={language}
        onChange={(e) => changeLanguage(e.target.value)}
        aria-label={t('common:select_language')}
      >
        {availableLanguages.map(lang => (
          <option key={lang.code} value={lang.code}>
            {lang.name}
          </option>
        ))}
      </select>
    </div>
  );
}

Dla arabskiego, hebrajskiego i perskiego provider ustawia document.dir = 'rtl'. LanguageSelector to zwykły select sterowany z kontekstu.

Daty, liczby i waluty

Daty każdy kraj zapisuje inaczej, więc zamiast ręcznego formatowania użyj Intl.DateTimeFormat z językiem z i18n.language:

// DateFormatter.jsx
import { useTranslation } from 'react-i18next';

function DateFormatter({ date, format = 'short' }) {
  const { i18n } = useTranslation();

  const formatDate = (date, format) => {
    const formatOptions = {
      short: {
        year: 'numeric',
        month: 'short',
        day: 'numeric'
      },
      long: {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        weekday: 'long'
      },
      time: {
        hour: '2-digit',
        minute: '2-digit'
      },
      datetime: {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      }
    };

    return new Intl.DateTimeFormat(
      i18n.language,
      formatOptions[format]
    ).format(new Date(date));
  };

  return <span>{formatDate(date, format)}</span>;
}

// Użycie
function EventCard({ event }) {
  return (
    <div className="event-card">
      <h3>{event.title}</h3>
      <DateFormatter date={event.startDate} format="long" />
      <DateFormatter date={event.startTime} format="time" />
    </div>
  );
}

Kolejność dnia, miesiąca i roku oraz nazwy miesięcy dopasują się do języka same, bez żadnego if.

Liczby i waluty obsługuje analogicznie Intl.NumberFormat:

// NumberFormatter.jsx
import { useTranslation } from 'react-i18next';

function NumberFormatter({
  value,
  type = 'decimal',
  currency = 'USD',
  minimumFractionDigits = 0,
  maximumFractionDigits = 2
}) {
  const { i18n } = useTranslation();

  const formatNumber = (value, type) => {
    const options = {
      minimumFractionDigits,
      maximumFractionDigits
    };

    if (type === 'currency') {
      options.style = 'currency';
      options.currency = currency;
    } else if (type === 'percent') {
      options.style = 'percent';
    }

    return new Intl.NumberFormat(i18n.language, options).format(value);
  };

  return <span>{formatNumber(value, type)}</span>;
}

// PriceDisplay.jsx
function PriceDisplay({ price, currency, originalPrice }) {
  const { t } = useTranslation();

  return (
    <div className="price-display">
      <span className="current-price">
        <NumberFormatter
          value={price}
          type="currency"
          currency={currency}
        />
      </span>

      {originalPrice && originalPrice > price && (
        <span className="original-price">
          <NumberFormatter
            value={originalPrice}
            type="currency"
            currency={currency}
          />
        </span>
      )}

      {originalPrice && originalPrice > price && (
        <span className="discount">
          {t('product.discount', {
            percent: ((originalPrice - price) / originalPrice * 100).toFixed(0)
          })}
        </span>
      )}
    </div>
  );
}

Liczba 12345.5 to po polsku 12 345,5, a po angielsku 12,345.5. Waluta nie zmienia się razem z językiem, zmienia się tylko zapis.

Leniwe ładowanie tłumaczeń

LazyTranslation doładowuje przestrzeń przez loadNamespaces dopiero wtedy, gdy ekran jej potrzebuje, a w tym czasie pokazuje komunikat:

// LazyTranslation.jsx
import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';

function LazyTranslation({ namespace, children }) {
  const { i18n, ready } = useTranslation(namespace, { useSuspense: false });
  const [isLoading, setIsLoading] = useState(!ready);

  useEffect(() => {
    if (!ready) {
      i18n.loadNamespaces(namespace).then(() => {
        setIsLoading(false);
      });
    } else {
      setIsLoading(false);
    }
  }, [namespace, ready, i18n]);

  if (isLoading) {
    return <div className="loading">Ładowanie tłumaczeń...</div>;
  }

  return children;
}

// Użycie
function ProductPage() {
  return (
    <LazyTranslation namespace="products">
      <ProductDetails />
      <ProductReviews />
    </LazyTranslation>
  );
}

Flaga ready mówi, czy tłumaczenia dotarły. Ten wariant wyłącza Suspense opcją useSuspense: false, bo domyślnie hook sam wstrzymuje komponent.

Dlatego wygodniej użyć Suspense: useTranslation z domyślnym useSuspense: true zawiesza komponent do chwili załadowania przestrzeni:

// TranslationSuspense.jsx
import { Suspense } from 'react';
import { useTranslation } from 'react-i18next';

function TranslationLoader({ namespace, children }) {
  const { ready } = useTranslation(namespace, { useSuspense: true });

  if (!ready) {
    throw new Promise((resolve) => {
      // Symulacja ładowania
      setTimeout(resolve, 100);
    });
  }

  return children;
}

function App() {
  return (
    <div>
      <Suspense fallback={<div>Ładowanie tłumaczeń...</div>}>
        <TranslationLoader namespace="common">
          <Header />
        </TranslationLoader>
      </Suspense>

      <Suspense fallback={<div>Ładowanie treści strony...</div>}>
        <TranslationLoader namespace="dashboard">
          <Dashboard />
        </TranslationLoader>
      </Suspense>
    </div>
  );
}

Ręczne rzucanie obietnicy w TranslationLoader tylko ilustruje mechanizm, bo hook i tak wstrzyma renderowanie. Każda granica Suspense ładuje się niezależnie.

SEO i SSR

Przy SSR tłumaczenia muszą być gotowe, zanim HTML opuści serwer, inaczej wyszukiwarka zobaczy klucze. Przykład używa next-i18next 16 z Pages Routerem, którego API importujesz z next-i18next/pages:

// next-i18next.config.js
module.exports = {
  i18n: {
    defaultLocale: 'en',
    locales: ['en', 'pl', 'es', 'fr', 'de']
  },
  localePath: './public/locales',
  defaultNS: 'common',
  fallbackLng: {
    'en-US': ['en'],
    'pl-PL': ['pl'],
    default: ['en']
  }
};

// pages/_app.js
import { appWithTranslation } from 'next-i18next/pages';
import { LanguageProvider } from '../components/LanguageProvider';

function MyApp({ Component, pageProps }) {
  return (
    <LanguageProvider>
      <Component {...pageProps} />
    </LanguageProvider>
  );
}

export default appWithTranslation(MyApp);

// pages/index.js
import { serverSideTranslations } from 'next-i18next/pages/serverSideTranslations';
import { useTranslation } from 'next-i18next/pages';

function HomePage() {
  const { t } = useTranslation('common');

  return (
    <div>
      <h1>{t('welcome.title')}</h1>
      <p>{t('welcome.description')}</p>
    </div>
  );
}

export async function getStaticProps({ locale }) {
  return {
    props: {
      ...(await serverSideTranslations(locale, ['common', 'navigation']))
    }
  };
}

export default HomePage;

serverSideTranslations ładuje przestrzenie na serwerze, a appWithTranslation przekazuje je aplikacji. Obiekt i18n z konfiguracji trafia też do next.config.js, a Next.js przyjmuje w nim tylko własne pola, jak locales i defaultLocale, dlatego opcje biblioteki (localePath, defaultNS, fallbackLng) leżą obok niego. Dla App Routera wersja 16 ma osobne API: getT() w komponentach serwerowych i useT() w klienckich.

LocalizedHead tłumaczy meta tagi i mówi wyszukiwarce, że strona istnieje w kilku językach:

// LocalizedHead.jsx
import Head from 'next/head';
import { useTranslation } from 'next-i18next/pages';
import { useRouter } from 'next/router';

function LocalizedHead({
  title,
  description,
  keywords,
  ogImage,
  canonical
}) {
  const { t, i18n } = useTranslation('meta');
  const router = useRouter();

  const localizedTitle = title ? t(title) : t('default.title');
  const localizedDescription = description ? t(description) : t('default.description');
  const localizedKeywords = keywords ? t(keywords) : t('default.keywords');

  const currentUrl = `https://example.com${router.asPath}`;
  const canonicalUrl = canonical || currentUrl;

  return (
    <Head>
      <title>{localizedTitle}</title>
      <meta name="description" content={localizedDescription} />
      <meta name="keywords" content={localizedKeywords} />
      <meta name="language" content={i18n.language} />

      {/* Open Graph */}
      <meta property="og:title" content={localizedTitle} />
      <meta property="og:description" content={localizedDescription} />
      <meta property="og:url" content={currentUrl} />
      <meta property="og:locale" content={i18n.language} />
      <meta property="og:image" content={ogImage} />

      {/* Twitter Card */}
      <meta name="twitter:title" content={localizedTitle} />
      <meta name="twitter:description" content={localizedDescription} />

      {/* Canonical URL */}
      <link rel="canonical" href={canonicalUrl} />

      {/* Alternate language versions */}
      {i18n.options.locales?.map(locale => (
        <link
          key={locale}
          rel="alternate"
          hrefLang={locale}
          href={`https://example.com/${locale}${router.asPath}`}
        />
      ))}
    </Head>
  );
}

Link rel="alternate" z atrybutem hrefLang wskazuje każdą wersję językową, a og:locale podaje język serwisom społecznościowym.

Testy

W testach nie ładujesz plików przez HTTP. Własny render owija komponent w I18nextProvider, a konfiguracja testowa podaje tłumaczenia przez resources i ustawia lng: 'en':

// test-utils.js
import { render } from '@testing-library/react';
import { I18nextProvider } from 'react-i18next';
import i18n from './i18n-test-config';

const AllTheProviders = ({ children }) => {
  return (
    <I18nextProvider i18n={i18n}>
      {children}
    </I18nextProvider>
  );
};

const customRender = (ui, options) =>
  render(ui, { wrapper: AllTheProviders, ...options });

export * from '@testing-library/react';
export { customRender as render };

// i18n-test-config.js
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';

i18n.use(initReactI18next).init({
  lng: 'en',
  fallbackLng: 'en',
  defaultNS: 'common',
  debug: false,
  interpolation: {
    escapeValue: false
  },
  resources: {
    en: {
      common: {
        'welcome.title': 'Welcome',
        'button.submit': 'Submit'
      }
    },
    pl: {
      common: {
        'welcome.title': 'Witaj'
      }
    }
  }
});

export default i18n;

// Component.test.js
import { render, screen } from './test-utils';
import { act } from '@testing-library/react';
import i18n from './i18n-test-config';
import WelcomeComponent from './WelcomeComponent';

describe('WelcomeComponent', () => {
  test('renders welcome message', () => {
    render(<WelcomeComponent />);

    expect(screen.getByText('Welcome')).toBeInTheDocument();
  });

  test('changes language', async () => {
    const { rerender } = render(<WelcomeComponent />);

    // Zmień język
    await act(async () => {
      await i18n.changeLanguage('pl');
    });

    rerender(<WelcomeComponent />);

    expect(screen.getByText('Witaj')).toBeInTheDocument();
  });
});

To ten sam łańcuch use(initReactI18next).init() co w aplikacji, tylko bez backendu. defaultNS: 'common' wskazuje przestrzeń z kluczami testowymi, a resources zawiera oba języki, które sprawdza test. Test zmiany języka czeka w act, aż React przerenderuje komponent.

Wydajność

Przy długich listach OptimizedTranslation łączy memo z useMemo, a useTranslationCache trzyma gotowe teksty w mapie:

// OptimizedTranslation.jsx
import { memo, useMemo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';

const OptimizedTranslation = memo(function OptimizedTranslation({
  translationKey,
  values,
  namespace = 'common'
}) {
  const { t } = useTranslation(namespace);

  const translatedText = useMemo(() => {
    return t(translationKey, values);
  }, [t, translationKey, values]);

  return <span>{translatedText}</span>;
});

// TranslationCache.jsx - Custom hook z cache
function useTranslationCache() {
  const { t, i18n } = useTranslation();
  const cache = useMemo(() => new Map(), [i18n.language]);

  const getCachedTranslation = useCallback((key, options) => {
    const cacheKey = JSON.stringify({ key, options });

    if (cache.has(cacheKey)) {
      return cache.get(cacheKey);
    }

    const translation = t(key, options);
    cache.set(cacheKey, translation);

    return translation;
  }, [t, cache]);

  return getCachedTranslation;
}

Cache powstaje od nowa przy zmianie i18n.language, więc stare teksty nie przeciekną do nowego języka. Najpierw jednak zmierz, bo zwykle to przedwczesna optymalizacja.

Pliki tłumaczeń możesz wydzielić do osobnej paczki albo ładować dynamicznym import():

// webpack.config.js
module.exports = {
  optimization: {
    splitChunks: {
      cacheGroups: {
        i18n: {
          test: /[\\/]locales[\\/]/,
          name: 'i18n',
          chunks: 'all'
        }
      }
    }
  }
};

// Dynamic imports dla tłumaczeń
const loadTranslations = async (language) => {
  const translations = await import(`../locales/${language}/common.json`);
  return translations.default;
};

splitChunks zbiera katalog locales w plik i18n, a loadTranslations pobiera naraz tylko jeden język.

Najlepsze praktyki

Klucze grupuj według miejsca w aplikacji, czyli stron, komponentów i wspólnych akcji:

// Dobra struktura
{
  "pages": {
    "home": {
      "title": "Home Page",
      "meta": {
        "description": "Welcome to our homepage"
      }
    },
    "about": {
      "title": "About Us",
      "sections": {
        "team": "Our Team",
        "history": "Company History"
      }
    }
  },
  "components": {
    "navigation": {
      "menu": "Menu",
      "close": "Close"
    },
    "forms": {
      "validation": {
        "required": "This field is required",
        "email": "Please enter a valid email"
      }
    }
  },
  "common": {
    "actions": {
      "save": "Save",
      "cancel": "Cancel",
      "delete": "Delete"
    }
  }
}

Wspólne słowa, jak Save czy Cancel, trzymasz wtedy w jednym miejscu: common.actions.

Własny hook ogranicza t() do kluczy z interfejsu TranslationKeys, więc literówka zatrzyma kompilację:

// types/i18n.ts
export interface TranslationKeys {
  'welcome.title': string;
  'welcome.description': string;
  'navigation.home': string;
  'navigation.about': string;
  'forms.name.label': string;
  'forms.email.label': string;
}

// Custom hook z typowaniem
import { useTranslation as useI18nTranslation } from 'react-i18next';

export function useTranslation(namespace?: string) {
  const { t, ...rest } = useI18nTranslation(namespace);

  return {
    t: (key: keyof TranslationKeys, options?: any) => t(key, options),
    ...rest
  };
}

// Komponenty z typowaniem
interface TranslatedTextProps {
  translationKey: keyof TranslationKeys;
  values?: Record<string, any>;
}

function TranslatedText({ translationKey, values }: TranslatedTextProps) {
  const { t } = useTranslation();
  return <span>{t(translationKey, values)}</span>;
}

Dokumentacja react-i18next opisuje też pełne typowanie przez interfejs CustomTypeOptions, który wyprowadza klucze z plików JSON. W większym projekcie polecam ten sposób.

Organizację tłumaczeń, wydajność i testy scenariuszy językowych sprawdzisz w ćwiczeniu, budując wielojęzyczny dashboard kosmiczny.

Pamiętaj: komponent zna tylko klucze, a pliki tłumaczeń to słowniki tłumacza pokładowego - wymieniasz słownik, a statek mówi nowym językiem.

Kod do tej lekcji: App.jsx
import React, { useState, createContext, useContext } from 'react';

// Symulacja biblioteki i18n - system tłumaczeń
const translations = {
  pl: {
    welcome: 'Witaj na stacji kosmicznej!',
    language: 'Język',
    mission: 'Aktualna misja',
    missionDesc: 'Eksploracja nowych galaktyk',
    crew: 'Załoga',
    crewMembers: '{count} członków',
    status: 'Status systemu',
    online: 'Online',
    fuel: 'Paliwo: {level}%',
    date: 'Data gwiezdna',
  },
  en: {
    welcome: 'Welcome to the space station!',
    language: 'Language',
    mission: 'Current mission',
    missionDesc: 'Exploring new galaxies',
    crew: 'Crew',
    crewMembers: '{count} members',
    status: 'System status',
    online: 'Online',
    fuel: 'Fuel: {level}%',
    date: 'Star date',
  },
  de: {
    welcome: 'Willkommen auf der Raumstation!',
    language: 'Sprache',
    mission: 'Aktuelle Mission',
    missionDesc: 'Erforschung neuer Galaxien',
    crew: 'Besatzung',
    crewMembers: '{count} Mitglieder',
    status: 'Systemstatus',
    online: 'Online',
    fuel: 'Treibstoff: {level}%',
    date: 'Sternendatum',
  },
};

// Kontekst i18n
const I18nContext = createContext(null);

function I18nProvider({ children }) {
  const [locale, setLocale] = useState('pl');

  const t = (key, params = {}) => {
    let text = translations[locale]?.[key] || key;
    Object.entries(params).forEach(([k, v]) => {
      text = text.replace('{' + k + '}', v);
    });
    return text;
  };

  return (
    <I18nContext.Provider value={{ locale, setLocale, t }}>
      {children}
    </I18nContext.Provider>
  );
}

function useTranslation() {
  return useContext(I18nContext);
}

function LanguageSwitcher() {
  const { locale, setLocale } = useTranslation();
  const languages = [
    { code: 'pl', flag: 'PL', label: 'Polski' },
    { code: 'en', flag: 'EN', label: 'English' },
    { code: 'de', flag: 'DE', label: 'Deutsch' },
  ];

  return (
    <div style={{ display: 'flex', gap: '8px' }}>
      {languages.map(lang => (
        <button
          key={lang.code}
          onClick={() => setLocale(lang.code)}
          style={{
            padding: '8px 16px',
            border: locale === lang.code ? '2px solid #00d4ff' : '1px solid #415a77',
            borderRadius: '8px',
            background: locale === lang.code ? '#1b2838' : 'transparent',
            color: locale === lang.code ? '#00d4ff' : '#778da9',
            cursor: 'pointer',
            fontWeight: locale === lang.code ? 'bold' : 'normal',
          }}
        >
          {lang.flag} {lang.label}
        </button>
      ))}
    </div>
  );
}

function SpaceStationDashboard() {
  const { t, locale } = useTranslation();
  const crewCount = 7;
  const fuelLevel = 82;
  const starDate = new Date().toLocaleDateString(locale, {
    year: 'numeric', month: 'long', day: 'numeric',
  });

  return (
    <div style={{ background: '#0d1b2a', minHeight: '100vh', padding: '24px', color: '#e0e1dd', fontFamily: 'monospace' }}>
      <div style={{ maxWidth: '600px', margin: '0 auto' }}>
        <h1 style={{ color: '#00d4ff', marginBottom: '8px' }}>{t('welcome')}</h1>

        <div style={{ marginBottom: '24px' }}>
          <h3 style={{ color: '#778da9', marginBottom: '8px' }}>{t('language')}</h3>
          <LanguageSwitcher />
        </div>

        <div style={{ display: 'grid', gap: '16px' }}>
          <div style={{ background: '#1b2838', padding: '16px', borderRadius: '12px', border: '1px solid #415a77' }}>
            <h3 style={{ color: '#00d4ff', margin: '0 0 8px' }}>{t('mission')}</h3>
            <p style={{ margin: 0, color: '#e0e1dd' }}>{t('missionDesc')}</p>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
            <div style={{ background: '#1b2838', padding: '16px', borderRadius: '12px', border: '1px solid #415a77' }}>
              <h4 style={{ color: '#778da9', margin: '0 0 4px' }}>{t('crew')}</h4>
              <p style={{ color: '#00d4ff', fontSize: '20px', margin: 0 }}>
                {t('crewMembers', { count: crewCount })}
              </p>
            </div>
            <div style={{ background: '#1b2838', padding: '16px', borderRadius: '12px', border: '1px solid #415a77' }}>
              <h4 style={{ color: '#778da9', margin: '0 0 4px' }}>{t('status')}</h4>
              <p style={{ color: '#00ff88', fontSize: '20px', margin: 0 }}>{t('online')}</p>
            </div>
          </div>

          <div style={{ background: '#1b2838', padding: '16px', borderRadius: '12px', border: '1px solid #415a77' }}>
            <h4 style={{ color: '#778da9', margin: '0 0 4px' }}>{t('fuel', { level: fuelLevel })}</h4>
            <div style={{ background: '#0d1b2a', borderRadius: '8px', height: '20px', overflow: 'hidden' }}>
              <div style={{ width: fuelLevel + '%', height: '100%', background: 'linear-gradient(90deg, #00d4ff, #00ff88)', borderRadius: '8px' }} />
            </div>
          </div>

          <div style={{ background: '#1b2838', padding: '16px', borderRadius: '12px', border: '1px solid #415a77' }}>
            <h4 style={{ color: '#778da9', margin: '0 0 4px' }}>{t('date')}</h4>
            <p style={{ color: '#e0e1dd', fontSize: '18px', margin: 0 }}>{starDate}</p>
          </div>
        </div>
      </div>
    </div>
  );
}

export default function App() {
  return (
    <I18nProvider>
      <SpaceStationDashboard />
    </I18nProvider>
  );
}

Hasła z dokumentacji w tej lekcji

Widzisz błąd w tej lekcji?

Sprawdź się

Odpowiedz na pytania z tej lekcji. Wybierz odpowiedź, a od razu zobaczysz, czy jest poprawna.

  1. 1. Do czego służy hook useTranslation z biblioteki react-i18next?

  2. 2. Jak react-i18next obsługuje pluralizację (np. '1 element' vs '5 elementów')?

Zadania praktyczne w grze

  • Klikanie w kolejności

    Kliknij elementy w kolejności inicjalizacji i18next w aplikacji React:

  • Edytor kodu

    Uzupełnij mini wersję funkcji t() z i18next w kosmicznym dashboardzie (PL, EN, DE). ___BLANK1___: przekaż do new Intl.PluralRules(...) kod aktualnego języka, żeby polski wybierał formy one, few i many, a angielski i niemiecki one i other. ___BLANK2___: w miejsce {{name}} i {{count}} wstaw wartość z obiektu options (name to nazwa zmiennej z podwójnych nawiasów, np. count). ___BLANK3___: przycisk języka zapisuje w stanie swój kod (pl, en albo de). W podglądzie zobaczysz kolejno: 1 aktywna misja, 2 aktywne misje, 5 aktywnych misji, a po przełączeniu na EN: 5 active missions.

  1. Kliknij w kolejnościŁańcuch inicjalizacji i18next
  2. PytanieHook useTranslation w react-i18next
  3. PytaniePluralizacja w i18n
  4. Zadanie z kodemPraktyka: Dashboard i18n

Przydatne artykuły