Skip to main content
Version: 4.x.x

Using with Gatsby

To use Tolgee with Gatsby follow this Guide.

Prerequisites

  1. Created Gatsby project with installed @tolgee/react module
  2. Created project in Tolgee platform with 2 languages. In our case it is English (en) and Czech (cs).
  3. Added some localization key and translations for both languages. In our case the key name is hello_world
  4. Generated API key for your project
  5. Exported data as zip of jsons

Set up your environment.

Create file (if not exists) .env.development and add this content to it.

GATSBY_TOLGEE_API_KEY=<your api key>
GATSBY_TOLGEE_API_URL=https://app.tolgee.io

Then replace <your api key> with your generated API key.

Save exported data to project structure

Save exported json files to src/i18n folder in your project structure.

Use Intl extension

npm install -D gatsby-plugin-react-intl
gatsby-config.js
module.exports = {
plugins: [
{
resolve: `gatsby-plugin-react-intl`,
options: {
path: `${__dirname}/src/i18n`,
languages: [`en`, `cs`],
defaultLanguage: `en`,
redirect: true,
},
},
],
};

Use TolgeeProvider

import { useIntl } from 'gatsby-plugin-react-intl';

export const AppWrapper: React.FC = ({ children }) => {
const { locale, messages } = useIntl();

return (
<TolgeeProvider
forceLanguage={intl.locale}
apiKey={process.env.GATSBY_TOLGEE_API_KEY}
apiUrl={process.env.GATSBY_TOLGEE_API_URL}
staticData={{
en: () => import(`../i18n/en.json`),
cs: () => import('../i18n/cs.json'),
// translations provided by intl plugin
[locale]: messages,
}}
loadingFallback={<div>Loading...</div>}
>
{children}
</TolgeeProvider>
);
};

Intl plugin manages locale for us and also gives us content of localization file based on locale, which we provide statically to Tolgee. On production Gatsby will generate pages separately for each locale, so only locale that is needed is provided statically.

Change language with intl plugin

import { useCurrentLanguage } from '@tolgee/react';
import { changeLocale } from 'gatsby-plugin-react-intl';

export const LangSelector: React.FC = () => {
const getLang = useCurrentLanguage();

return (
<select
onChange={(e) => changeLocale(e.target.value)}
value={getLang()}
>
<option value="en">🇬🇧 English</option>
<option value="cs">🇨🇿 Česky</option>
</select>
);
};

You are done! Now you can translate your strings directly in your application, and enjoy the features of Gatsby in the same time! You can find final application code in this repo: github.com/tolgee/gatsby-example.

Now you can use translation methods described here.