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 initinit: script that creates aterai.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 (extractandtranslate) run byterai.
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 thetsfunction.
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 extractextract: 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 translatetranslate: script to translate your messages. Check more info about the translation process.
API
| Package | Version | Size | Downloads |
|---|---|---|---|
@terai/react |
Exports
import {
useTs,
useFormat,
useLocale,
setLocale,
setupTerai,
} from '@terai/react'setupTerai: Client-side configuration optionsuseFormat: Hook to get the format functionuseLocale: Hook to retrieve the current localeuseTs: Hook to retrieve thetsfunctionsetLocale: 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).