To load translations in your markdown files using React/Inertia and react-i18next, you can follow these steps:
-
Install the necessary packages:
-
react-i18next: This package provides the i18n functionality for React applications. -
i18next: This package is the core library for i18n functionality.
You can install these packages using npm or yarn:
npm install react-i18next i18next -
-
Set up the i18n configuration: In your main React file (e.g.,
App.js), import the necessary packages and set up the i18n configuration. This configuration will define the translation resources and language options.import React from 'react'; import { I18nextProvider } from 'react-i18next'; import i18n from 'i18next'; // Import your translation resources import translations from './translations'; // Set up i18n configuration i18n.init({ resources: translations, lng: 'en', // Set the default language fallbackLng: 'en', // Set the fallback language interpolation: { escapeValue: false, // React already escapes the values }, }); const App = () => { return ( <I18nextProvider i18n={i18n}> {/* Your app components */} </I18nextProvider> ); }; export default App;In the above example,
translationsis an object that contains your translation resources. You can define translations for different languages in this object. -
Create your translation resources: In a separate file (e.g.,
translations.js), define your translation resources using the i18next format. Each translation resource should have a key-value pair, where the key represents the translation key and the value represents the translated text.const translations = { en: { Emails: { emailtitle: 'Email Title', }, frontend: { text1: 'Text 1', }, }, // Add translations for other languages if needed }; export default translations; -
Load translations in your markdown files: In your markdown files, you can use the
Transcomponent provided byreact-i18nextto load translations. TheTranscomponent allows you to interpolate variables and format the translated text.import { Trans } from 'react-i18next'; // ... <Trans i18nKey="Emails.emailtitle"> Email Title </Trans> // ... <Trans i18nKey="frontend.text1"> Text 1 </Trans>The
i18nKeyprop in theTranscomponent represents the translation key defined in your translation resources.Note: Make sure to wrap your markdown files with the
Transcomponent or any other component that provides the i18n context.
That's it! With this setup, you should be able to load translations in your markdown files using React/Inertia and react-i18next.