React usage

@18ways/react gives you the runtime primitives. The main job is to scope them cleanly.

Root mode vs scope mode

At the root, Ways owns the API key, locale, accepted locales, and shared translation store.

Nested Ways scopes only need context:

tsx
<Ways apiKey="pk_dummy_demo_token" locale="es-ES" baseLocale="en-GB" context="checkout">
  <Ways context="payment-form">
    <PaymentForm />
  </Ways>
</Ways>

Nếu một cây con cần phiên locale riêng, hãy cấp cho nó một root riêng thay vì dựa vào ghi đè locale theo phạm vi:

tsx
<Ways apiKey="pk_dummy_demo_token" locale="en-GB" baseLocale="en-GB" context="app">
  <MarketingSite />
 
  <Ways apiKey="pk_dummy_demo_token" locale="ja-JP" baseLocale="en-GB" context="hero-demo">
    <EmbeddedLocaleDemo />
  </Ways>
</Ways>

Root lồng nhau đó sẽ có locale được chọn, trạng thái đang tải và store đã hydrate riêng.

Loading state

If you want to reflect translation work in the UI, use useTranslationLoading().

tsx
import { useTranslationLoading } from '@18ways/react';
 
function SavePanel() {
  const isTranslationLoading = useTranslationLoading();
 
  return <span>{isTranslationLoading ? 'Loading translations...' : 'Ready'}</span>;
}

useTranslationLoading() chỉ theo dõi công việc chặn cho ngữ cảnh hiện tại. Các điều khiển ở cấp root như LanguageSwitcher đã đọc trạng thái đang tải của runtime gốc cho bạn.

Suspense

<T>useT() sẽ ném tới ranh giới React hoặc framework gần nhất khi một lượt đọc không thuộc chuyển tiếp vẫn đang chờ. Trong một lần chuyển locale thực sự, chúng vẫn tiếp tục render locale đã ổn định trước đó thông qua fallback của store thay vì bị treo. Công việc chặn bị giới hạn bởi suspenseTimeoutMs, sau đó việc render tiếp tục với phương án dự phòng tốt nhất hiện có trong khi việc tải bản dịch vẫn diễn ra ngầm ở nền.

Locale hooks

The root runtime exposes two low-level hooks:

tsx
import { useCurrentLocale, useSetCurrentLocale } from '@18ways/react';

Use them when you want to build your own locale controls instead of LanguageSwitcher.

LanguageSwitcher

The built-in switcher is controlled and composable.

tsx
<LanguageSwitcher currentLocale={locale} onLocaleChange={setLocale} direction="down" />

Nó đọc danh sách locale đã chấp nhận từ runtime gốc và xử lý trạng thái đang tải trong lúc locale tiếp theo đang được phân giải. Trong quá trình chuyển locale, UI đã dịch vẫn tiếp tục dùng locale đã ổn định gần nhất làm phương án dự phòng cho đến khi locale tiếp theo sẵn sàng.

Component composition

Keep the sentence together and let <T> preserve the UI shape.

tsx
<T>
  <a href="/pricing">Click here</a> to see more
</T>

Message formatter escape hatches

The default formatter is waysParser. Only switch away from it if you have a concrete reason.

  • messageFormatter="none" leaves strings alone.
  • a custom formatter function lets you own interpolation fully.

That should be rare.

Đang đổi ngôn ngữ
Cách dùng React