The translate function

Translate content outside JSX with the translate function

Sometimes you need to translate content in your React application that's not part of your JSX templates. One example is the metadata of a Next.js application.

Luckily this is no problem with Magic Translate and can easily be achieved with the translate function that is set up when preparing Magic Translate for SSR.

As documented on the React SSR page, to get started you needed to set up the translate function and the <T> component, like so:

import { createT, setupTranslate } from "@magic-translate/react-ssr";

const magicTranslateConfig = {
  apiKey: "<your-api-key>",
}

// the translate function!
export const translate = setupTranslate(magicTranslateConfig);

export const T = createT(translate);

The translate function set up here is just a plain function that takes a language, a text and optional options as input parameters and returns the translation of the string asynchronously.

const translation = await translate(
    Language.ZH,
    'This sentence will be translated to Chinese'
)

Going back to the example of Next.js metadata, here's how you could translate your metadata with the translate function:

import { Metadata, NextPage } from 'next';
import { Language } from '@magic-translate/react-ssr'

export async function generateMetadata(
  { params }: { params: { lang : Language } }): Promise<Metadata> {
  return {
    title: await translate(
      params.lang,
      'This page title will be translated'
    ),
  };
}

Last updated