Installation
To use Tolgee in your React application, you need to follow these steps:
Install the Tolgee SDK
To install Tolgee's React integration SDK, execute the following command:
- npm
- yarn
- pnpm
npm install @tolgee/react
yarn add @tolgee/react
pnpm install @tolgee/react
Configure the Tolgee API
Once the SDK is installed, you need to initialize it. For the initialization, you need the Tolgee API URL, and the Tolgee API Key. To generate the API Key, follow the step-by-step instructions mentioned on the API keys and PAT tokens page.
Make sure you don't leak your API key. If the API key is leaked, visitors can edit the translations on your site.
After generating the API key, add these credentials in your .env
file. Your .env
should look like this:
VITE_APP_TOLGEE_API_URL=https://app.tolgee.io
VITE_APP_TOLGEE_API_KEY=tgpak_gfpwiojtnrztqmtbna3dczjxny2ha3dmnu4tk4tnnjvgc
If you are using a React-based framework like Next.js, make sure you paste these credentials in the correct file.
Add the Tolgee Provider
Next, use the above credentials to initialize Tolgee in your React application. You can use Tolgee across your React application by using the TolgeeProvider
.
Wrap your App
component within the TolgeeProvider, as show in the code below.
import { Tolgee, DevTools, TolgeeProvider, FormatSimple } from "@tolgee/react";
const tolgee = Tolgee()
.use(DevTools())
.use(FormatSimple())
// replace with .use(FormatIcu()) for rendering plurals, foramatted numbers, etc.
.init({
language: 'en',
// for development
apiUrl: process.env.VITE_APP_TOLGEE_API_URL,
apiKey: process.env.VITE_APP_TOLGEE_API_KEY,
// for production
staticData: {
...
}
});
...
<TolgeeProvider
tolgee={tolgee}
fallback="Loading..." // loading fallback
>
<App/>
</TolgeeProvider>
The above code does the following:
- Imports the required classes, plugins and the TolgeeProvider from the SDK.
- Creates a new instance of Tolgee, configures it to use the DevTools and FormatSimple plugins, and initializes it using the credentials.
- Passes the instance to the TolgeeProvider and sets a fallback.
- Uses TolgeeProvider to wrap the component.
You can configure more options and plugins during initialization. Learn about these other options and Tolgee plugins in their respective documentation.
Prepare for production
Tolgee will automatically omit DevTools
from your bundle when you build your app for production. So it won't fetch translations directly from Tolgee Platform and it won't allow users to modify translations.
There are generally two ways how to use translations in production:
- Tolgee Content Delivery - translations are loaded dynamically from fast and reliable storage
- Providing localization files directly - your translations are bundled with your code
In production mode, you should never use localization data directly from Tolgee REST API, because it can negatively affect your page performance.