Documentation

The translate function

Sometimes you need to translate content that isn't part of your JSX, for example the metadata of a Next.js page. The t() function returned by createLocalizedT translates any string.

import type { Metadata } from 'next';
import { createLocalizedT } from '@magic-translate/react-ssr';
import { translate } from '@/lib/translate';
export async function generateMetadata({
params
}: {
params: Promise<{ locale: string }>;
}): Promise<Metadata> {
const { locale } = await params;
const { t } = createLocalizedT(translate, locale);
return {
title: await t('This page title will be translated'),
description: await t('And so will this description')
};
}

You can also call the translate function from the setup directly. It accepts a language, the text to translate and an optional settings object, and returns a promise that resolves to the translation.

import { Language } from '@magic-translate/react-ssr';
const translation = await translate(
Language.ZH,
'This sentence will be translated to Chinese'
);

Both take an id, to edit this use of the text on its own:

const title = await t('Save', { id: 'checkout-save' });
const translation = await translate(Language.DE, 'Save', {
id: 'checkout-save'
});