Magic Translate
  • Getting started
  • Clients
    • React
      • The <T> component
      • The useT hook
      • Next.js
    • React SSR
      • The translate function
  • FAQs
    • How fast is the translation
    • How is the usage calculated
    • What are the limitations
    • What happens when the monthly limit is reached?
    • What are the available languages?
Powered by GitBook
On this page
  1. Clients
  2. React SSR

The translate function

Translate content outside JSX with the translate function

PreviousReact SSRNextFAQs

Last updated 1 year ago

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 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'
    ),
  };
}
React SSR