Translating strings

How to translate strings

Overview

This guide is a step-by-step tutorial on how to translate strings in your Next.js app using useGT, getGT, and tx.

Prerequisites

We assume you’ve already installed gt-next in your project and have followed, or are currently following, the Quick Start Guide.

Translating strings

Client‑side components

For any client‑side strings, use useGT. Remember that useGT must be called within a child component of <GTProvider>.

src/components/MyComponent.jsx
import { useGT } from 'gt-next';

export default function MyComponent() {
  const t = useGT(); 
  return (
    <div>
      <h1>{t('This is a string that gets translated')}</h1> // [!code highlight]
    </div>
  );
}

Server‑side Components

For any server‑side strings, use getGT.

src/pages/index.jsx
import { getGT } from 'gt-next/server';

export default async function Home() {
  const t = await getGT(); 
  return (
    <div>
      <h1>{t('This is a string that gets translated')}</h1> // [!code highlight]
    </div>
  );
}

Note: In development, if you translate content at runtime, you’ll need to refresh the page to see the translated version of a string from getGT. This does not happen in production.

Adding variables

Variables are values that may change but are not translated. To add variables to your strings, use the following pattern:

MyComponent.jsx
import { useGT } from 'gt-next';

export default function MyComponent() {
  const t = useGT();
  return (
    <div>
      <h1>{t('Hello there, {username}', { variables: { username: 'Brian123' }})}</h1> // [!code highlight]
    </div>
  );
}

This works with both useGT and getGT.

Dynamic Content

Suppose you have a string that changes. You can use the tx function to translate the string at runtime.

MyComponent.jsx
import { tx } from 'gt-next/server';

export default async function MyComponent({ username }) {
  const translation = await tx(`Hello, ${username}. How is your day?`); 
  return (
    <div>
      <h1>{translation}</h1> // [!code highlight]
    </div>
  );
}

Note: The tx function is only available on the server side and should only be used when necessary. Runtime translation often introduces a delay. Use getGT or useGT whenever possible to translate before deployment.


Notes

  • To translate strings, use useGT, getGT, and tx.
  • useGT and getGT translate before deployment, whereas tx translates at runtime. Use tx sparingly.
  • Variables can be added to strings using the { variables: { key: value } } pattern.

Next steps

How is this guide?

Translating strings