@k8ordo/i18n

Messages

Declare messages with message, call them from components, give them values, and hand their text from a Server Component to a Client Component.

On this page

Plain messages

src/messages/nav.ts
import { message } from '@k8ordo/i18n';

export const home = message({ ja: 'ホーム', en: 'Home' });

export const search = message({ ja: '検索', en: 'Search' });

Key the text by locale. message returns a function of no arguments, and it reads the current locale each time it is called.

ts
export const save = message({ ja: '保存' });
No en: a type error

Once Register carries the locale type, a message missing any of the locales is a type error. So is a message with a locale outside them.

When nothing names a locale, the default locale’s text is returned. When that happens is listed under Locales.

Messages with values

src/messages/cart.ts
import { message } from '@k8ordo/i18n';

export const added = message({
  ja: (name: string) => `${name}をカートに入れました`,
  en: (name) => `Added ${name} to your cart`,
});

A message that takes values is a function of the same arguments in every locale. A locale that does not use the value is a function too, and still declares the parameter, as in (_count) => 'Items'. A function that leaves it out either fails to compile or slips past the check, depending on which locale holds it. Text and functions cannot be mixed in one message.

Interpolation is a template literal. Annotate the argument types in one locale, and every other locale is checked against them. So is every value a caller passes.

src/lib/cart-notice.ts
import { added } from '../messages/cart';

added('Lamp');
added(3);
A number does not compile

Plurals, dates and numbers are written with Intl inside the function. See Formatting.

Warning

Pitfall

With no annotation in any locale, the arguments are unknown and any value passes. Annotate at least one locale, or pass the types as a type argument: message<[name: string]>({ … }).

Where to put messages

src/components/header.tsx
import { home, search } from '../messages/nav';

export function Header() {
  return (
    <nav>
      <a href="/">{home()}</a>
      <a href="/search">{search()}</a>
    </nav>
  );
}

Messages can go in any file. Put one file per area in src/messages/, and import the messages a module needs by name. When two files export the same name, rename one on import: import { title as cartTitle }.

A message only one component uses can be declared in that component’s own module. Related messages can also be grouped in an object, but unused ones then stay in the bundle with it.

Where to call it

src/lib/menu.ts
import type { Message } from '@k8ordo/i18n';

import { home, search } from '../messages/nav';

export const MENU = [home(), search()];
export const MENU: readonly Message[] = [home, search];

Called at the top level of a module, a message’s string is fixed in the locale of that moment.

On the server, a module usually loads before any locale is set, so the string is in the default locale. In the browser, it stays in the locale of the URL the module loaded under, even after the language is switched.

Keep the Message and call it in the component that renders it.

Message props

src/components/nav-list.tsx
import type { Message } from '@k8ordo/i18n';

type NavItem = { href: string; label: Message };

export function NavList({ items }: { items: readonly NavItem[] }) {
  return (
    <ul>
      {items.map((item) => (
        <li key={item.href}>
          <a href={item.href}>{item.label()}</a>
        </li>
      ))}
    </ul>
  );
}

A component that takes a message types the prop as Message and calls it when it renders.

For a message that takes values, write the argument tuple as the type argument: Message<[name: string]>. Only the rendering component turns it into a string, so the code that builds the data never needs the locale.

Passing to the client

A message is a function, so it cannot be passed as a prop from a Server Component to a Client Component. React cannot serialize a function, and the render fails with Functions cannot be passed directly to Client Components.

A string prop

src/components/share-section.tsx
import { copied, copyLink } from '../messages/share';
import { CopyLink } from './copy-link';

export function ShareSection() {
  return <CopyLink copied={copied()} label={copyLink()} />;
}
src/components/copy-link.tsx
'use client';

import { useState } from 'react';

type Props = { copied: string; label: string };

export function CopyLink({ copied, label }: Props) {
  const [done, setDone] = useState(false);

  return (
    <button
      onClick={() => {
        void navigator.clipboard.writeText(location.href).then(() => {
          setDone(true);
        });
      }}
      type="button"
    >
      {done ? copied : label}
    </button>
  );
}

ShareSection, a Server Component, calls the messages and passes the strings in the current locale. The messages themselves stay out of the browser bundle.

Information

Note

After a build, search the JavaScript sent to the browser to confirm that text only a Server Component renders is not there.

Direct import

src/components/copy-link.tsx
'use client';

import { useState } from 'react';

import { copied, copyLink } from '../messages/share';

export function CopyLink() {
  const [done, setDone] = useState(false);

  return (
    <button
      onClick={() => {
        void navigator.clipboard.writeText(location.href).then(() => {
          setDone(true);
        });
      }}
      type="button"
    >
      {done ? copied() : copyLink()}
    </button>
  );
}

A Client Component can also import the message and call it itself. That message then ships to the browser with its text in every locale.

This suits text the browser decides: text that follows input, or text shown after a click.

Which messages reach the browser bundle is covered in How it works.

No directive

A component without a directive runs on the server when a Server Component renders it, and in the browser when a Client Component does. In both cases the props are not serialized, so a Message prop is fine.

A component that only reads props and messages, such as a page title, is left without 'use client'.

k8ordo

React libraries that use Baseline features without holding back.