Docs
Usage
React

Using Terai with React

Using Terai in a React project.

Installation

Install terai

Install terai and create your terai.config.ts file.

pnpm add -D @terai/dev
pnpm add @terai/react
pnpm terai init
  • init: script that creates a terai.config.ts.

Configure your options

terai.config.ts

Add your custom options in terai.config.ts. In this example we will use ChatGPT for translating out messages.

terai.config.ts
import { defineConfig, createChatGptTranslator } from '@terai/dev'
 
const translator = createChatGptTranslator({
  apiKey: process.env.OPEN_API_KEY,
})
 
export default defineConfig({
  include: ['./src/**/*.{js,jsx,ts,tsx}'],
  exclude: [],
  projectLocale: 'en',
  outDir: './locale-system',
  outLocales: ['es', 'it'],
  translator,
})
  • config: Options used by the static processes (extract and translate) run by terai.

setupTerai

Configure your runtime options by adding the following lines in your main entrypoint:

main.tsx
import React, { Suspense } from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.tsx'
import './index.css'
import { setupTerai } from '@terai/react'
 
setupTerai({
  defaultLocale: 'en',
  persist: true,
  loader: (locale: string, chunkId: string) =>
    import(`../locale-system/${locale}/${chunkId}.json`).then(
      (mod) => mod.default
    ),
})
 
ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <Suspense>
      <App />
    </Suspense>
  </React.StrictMode>
)
  • setupTerai: Client-side options used by the ts function.

Usage

Use terai

Now you can start using terai in your project. Here is the snippet of code that you can use in some example.tsx file.

example.tsx
import { useTs } from '@terai/react'
 
export function Example() {
  const { ts } = useTs()
 
  return (
    <div>
      <p>{ts`Hello, world!`}</p>
    </div>
  )
}

Extract

Once you're ready for your messages to be gathered, just run the extract script provided by the CLI.

pnpm terai extract
  • extract: script to statically extract messages from your project. Check more info about the extraction process.

Translate

Once you're ready for your messages to be gathered, just run the translate script provided by the CLI.

pnpm terai translate
  • translate: script to translate your messages. Check more info about the translation process.

API

PackageVersionSizeDownloads
@terai/reactVersion (opens in a new tab)Size (opens in a new tab)NPM (opens in a new tab)

Exports

import {
  useTs,
  useFormat,
  useLocale,
  setLocale,
  setupTerai,
} from '@terai/react'
  • setupTerai: Client-side configuration options
  • useFormat: Hook to get the format function
  • useLocale: Hook to retrieve the current locale
  • useTs: Hook to retrieve the ts function
  • setLocale: Function to set the current locale

Example

Check this scattfolded example (opens in a new tab) in the examples repo (opens in a new tab).