Implementing internationalization (i18n) in Gatsby can be achieved through various methods, but the most common and recommended approach is to use the gatsby-plugin-react-i18next plugin. This plugin is built on top of the react-i18next library, providing robust internationalization support, including multilingual routing and server-side language detection. Here are the steps to implement this plugin in your Gatsby project:
Step 1: Install the required packages
First, install the necessary dependencies: gatsby-plugin-react-i18next, i18next, and react-i18next.
bashnpm install gatsby-plugin-react-i18next i18next react-i18next
Step 2: Configure gatsby-config.js
Next, add and configure the gatsby-plugin-react-i18next plugin in your gatsby-config.js file.
javascriptmodule.exports = { plugins: [ { resolve: `gatsby-plugin-react-i18next`, options: { localeJsonSourceName: `locale`, // Name given to the `gatsby-source-filesystem` plugin languages: [`en`, `de`], // List of supported languages defaultLanguage: `en`, // Default language siteUrl: `https://www.example.com`, i18nextOptions: { interpolation: { escapeValue: false, // Not required for React as it handles escaping by default }, keySeparator: false, nsSeparator: false, }, pages: [ { matchPath: '/:lang?/blog/:uid', getLanguageFromPath: true, excludeLanguages: ['es'], }, ], }, }, ], };
Step 3: Add language files
Create JSON language files, typically stored in the ./locales directory. For example, you can have en/translation.json and de/translation.json.
json// en/translation.json { "hello": "Hello" } // de/translation.json { "hello": "Hallo" }
Step 4: Use the useTranslation hook
In your components, integrate the useTranslation hook to enable translation functionality.
javascriptimport React from "react"; import { useTranslation } from "react-i18next"; const MyComponent = () => { const { t } = useTranslation(); return <h1>{t('hello')}</h1>; // Displays "Hello" or "Hallo" based on the current language }; export default MyComponent;
Step 5: Implement language switching
Add a language switcher component to allow users to manually select their preferred language.
javascriptimport React from "react"; import { useI18next } from "gatsby-plugin-react-i18next"; const LanguageSwitcher = () => { const { languages, changeLanguage } = useI18next(); return ( <div> {languages.map((lang) => ( <button key={lang} onClick={() => changeLanguage(lang)}> {lang} </button> ))} </div> ); }; export default LanguageSwitcher;
By following these steps, your Gatsby site will support multiple languages and achieve internationalization, significantly enhancing global accessibility.