Skip to content

Latest commit

 

History

History
193 lines (139 loc) · 5.72 KB

react.mdx

File metadata and controls

193 lines (139 loc) · 5.72 KB
title React
description Use SayKit with React, components, hooks, and server runtime

@saykit/react gives you:

  • <Say> and its sub-components, for messages in any component, server or client
  • <SayProvider> and useSay() for client components
  • withSay, getSay() and setSay() for server components

<Say> is one import for both server and client: the package picks its build through the react-server export condition.

Install

pnpm add @saykit/react saykit
pnpm add -D @saykit/config @saykit/format-po @saykit/transform-js @saykit/transform-jsx unplugin-saykit

Then add a plugin: unplugin-saykit for Vite and similar (including TanStack Start), or babel-plugin-saykit for Next.js, Expo and React Native.

<Say>

import { Say } from '@saykit/react';

<Say>
  {items} items &middot; total <strong>{total}</strong>
</Say>;

Variables become named placeholders ({items}), and elements become numbered tags (<0>{total}</0>) that translators can move. A childless element extracts as <1/>. Plurals, select, numbers, dates and descriptors all have JSX forms, covered in Messages:

<Say.Plural _={count} one={<>{count} item</>} other={<>{count} items</>} />
<Say>Total <Say.Number _={total} style="::currency/EUR" /></Say>
<Say context="verb">Post</Say>

Naming tags

A number tells a translator nothing. Name a tag with say-tag:

<Say>
  Signed in as <strong say-tag="bold">{user}</strong>
</Say>

This extracts as Signed in as <bold>{user}</bold>. The attribute is stripped at build time. Name a tag after what it does to the text (bold, link, icon), not what it wraps, and use a static identifier.

Identical elements may share a name and compile to one prop. Elements that share a name but differ in any prop fail the build: name them link_docs and link_faq rather than link twice.

Client components

import { SayProvider, useSay } from '@saykit/react/client';

<SayProvider>

Render it once near the top of the client tree. In a browser app, give it a store, exported from your i18n module so everything that switches locale holds the same one:

import { createCatalogue, createStore } from 'saykit';
import en from './locales/en.js';
import fr from './locales/fr.js';

export const catalogue = createCatalogue({ en, fr });
export const store = createStore(catalogue, catalogue.match(navigator.languages));
<SayProvider store={store}>
  <App />
</SayProvider>

A server-rendered app sends a locale and its messages instead. A store cannot cross the server/client boundary, but compiled messages are plain data:

<SayProvider locale={locale} messages={messages}>
  {children}
</SayProvider>

That form holds one locale and cannot switch; switch by navigating. In a Next.js server component, withSay fills these props in for you.

useSay

The current view, for a string outside JSX. The component re-renders when the locale changes:

function DeleteButton({ count }: { count: number }) {
  const say = useSay();
  return <button onClick={() => confirm(say`Delete ${count} items?`)}>…</button>;
}

Switching locale

The store is a module value, so a picker imports it:

import { useSay } from '@saykit/react/client';
import { catalogue, store } from '../i18n';

function LocalePicker() {
  const say = useSay();
  return (
    <select value={say.locale} onChange={(event) => store.set(event.target.value)}>
      {catalogue.locales.map((locale) => (
        <option key={locale}>{locale}</option>
      ))}
    </select>
  );
}

Server components

import { createWithSay, getSay, setSay } from '@saykit/react/server';

withSay and getSay() are the server's <SayProvider> and useSay().

withSay

Bind it to your catalogue once:

export const withSay = createWithSay(catalogue);

withSay(Component, getLocale) matches and loads the locale getLocale returns, and establishes its view in React's per-request cache() before the component renders:

import { SayProvider } from '@saykit/react/client';
import { getSay } from '@saykit/react/server';
import { withSay } from '../../i18n';

function Layout({ children }: LayoutProps<'/[locale]'>) {
  return (
    <html lang={getSay().locale}>
      <body>
        <SayProvider>{children}</SayProvider>
      </body>
    </html>
  );
}

export default withSay(Layout, (props) => props.params.then((params) => params.locale));

<SayProvider> takes no props in a server component: its react-server build hands the established locale and messages to the client.

Wrap every layout and page that renders messages, not just the root. Next.js renders a page before its layout, so an unwrapped page's `getSay()` throws.

getSay

The view established for the request. Throws if there is none.

function Page() {
  const say = getSay();
  return <h1>{say`Welcome back!`}</h1>;
}

setSay

Establishes a view you resolved yourself:

setSay(await catalogue.load('fr'));
One view per request. A second view for another locale takes over for everything rendered after it, including what `` sends to the client, and development warns. To render another locale, pass its view (`await catalogue.load(locale)`) to the components that need it.

Next