Skip to main content

Using with Gatsby

To use Tolgee with Gatsby follow this Guide.

Prerequisites#

  1. Created Gatsby project with installed @tolgee/react and @tolgee/ui modules
  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';
import * as translationsEn from '../i18n/en.json';import * as translationsCs from '../i18n/cs.json';
export const AppWrapper: React.FC = ({ children }) => {  const intl = useIntl();
  return (    <TolgeeProvider      forceLanguage={intl.locale}      apiKey={process.env.GATSBY_TOLGEE_API_KEY}      apiUrl={process.env.GATSBY_TOLGEE_API_URL}      staticData={{        en: translationsEn,        cs: translationsCs,      }}      loadingFallback={<div>Loading...</div>}      ui={        process.env.GATSBY_TOLGEE_API_KEY ? require('@tolgee/ui').UI : undefined      }    >      {children}    </TolgeeProvider>  );};

The localization data is imported and provided to TolgeeProvider using staticData prop, so in production mode (when your page is built) Tolgee will use this data.

The forceLanguage prop forces Tolgee to use specific language. So here we are using intl plugin to manage selected language. To change language use the plugin build-in method.

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.