Back

gt-react@10.13.0

Ernest McCarter avatarErnest McCarter
gt-reactmacrotagged-templatedeveloper-experiencei18n

Overview

As part of our continued experimentation with moving away from React context, gt-react now supports using t as a tagged template literal:

import { t } from "gt-react/browser";

const greeting = t`Hello, ${name}!`;

This is an alternative syntax to the existing t() function call. Instead of writing ICU-style placeholders and passing an options object, you write a standard JavaScript template literal and variable interpolation is handled automatically.

Before and after

// Before — ICU placeholders + options object
t("Hello, {name}! You have {count} items.", { name, count })

// After — tagged template literal
t`Hello, ${name}! You have ${count} items.`

The tagged template form eliminates the need to name placeholders or duplicate variable references. You write your string the way you'd write any JavaScript template literal.

No React context required

Like the t() function introduced in gt-react@10.12.0, the tagged template form doesn't depend on React context. It works anywhere in browser code:

  • Event handlers: onClick={() => alert(t`Saved!`)}
  • Utility functions: function formatError(code) { return t`Error: ${code}` }
  • Constants and config: const LABELS = { save: t`Save`, cancel: t`Cancel` }
  • Outside React components entirely

Global registration

If you don't want to import t in every file, you can register it globally:

// In your app's entry point (e.g., layout.tsx)
import "gt-react/macros";

This sets globalThis.t, making the tagged template available everywhere without an explicit import.

Example

import { t } from "gt-react/browser";

export function Greeting({ name }) {
  return <p>{t`Hello, ${name}!`}</p>;
}

export function SaveButton() {
  return (
    <button onClick={() => alert(t`Changes saved!`)}>
      {t`Save`}
    </button>
  );
}

Or with global registration:

// No import needed — t is on globalThis
const LABELS = {
  save: t`Save`,
  cancel: t`Cancel`,
  delete: t`Delete`,
};