### Example configuration for testing without stubbing Source: https://react.i18next.com/misc/testing.md This i18next configuration initializes i18next with a test setup, including a common namespace and empty resources. It is used to test components without stubbing, by providing a real i18n instance to the provider. ```javascript import i18n from 'i18next'; import { initReactI18next } from 'react-i18next'; i18n .use(initReactI18next) .init({ lng: 'en', fallbackLng: 'en', // have a common namespace used around the full app ns: ['translationsNS'], defaultNS: 'translationsNS', debug: true, interpolation: { escapeValue: false, // not needed for react!! }, resources: { en: { translationsNS: {} } }, }); export default i18n; ``` -------------------------------- ### npm install react-i18next i18next and optional backends Source: https://react.i18next.com/latest/using-with-hooks.md Install react-i18next and i18next packages, and optionally i18next-http-backend and i18next-browser-languagedetector for user language detection and loading translations. ```bash npm install react-i18next i18next --save # if you'd like to detect user language and load translation npm install i18next-http-backend i18next-browser-languagedetector --save ``` -------------------------------- ### HTTP GET request with ask and goal parameters Source: https://react.i18next.com/llms.txt Use this HTTP GET request to ask a question about the documentation. The `ask` parameter is required and should be a specific, self-contained natural language question; `goal` is optional and describes the broader end goal. The response contains a direct answer with relevant excerpts and sources. ```http GET https://react.i18next.com/latest/typescript.md?ask=&goal= ``` -------------------------------- ### Install react-i18next and i18next with npm Source: https://react.i18next.com/getting-started.md Use this command to install both react-i18next and i18next as dependencies. The module is optimized for webpack and rollup, with correct entry points already configured in package.json. ```bash # npm $ npm install react-i18next i18next --save ``` -------------------------------- ### Using simple HTML elements in Trans (v10.4.0) Source: https://react.i18next.com/latest/trans-component.md Shows examples with strong, br, and Link component, with corresponding JSON translation strings. ```jsx Hello {{name}}. See my profile // JSON -> "welcomeUser": "Hello {{name}}. <1>See my profile" Some newlines
would be
fine
// JSON -> "multiline": "Some newlines
would be
fine" ``` -------------------------------- ### Trans component example Source: https://react.i18next.com/guides/quick-start.md Use the Trans component to translate a JSX tree, allowing translation of text containing components like links or formatting. The example shows a component and the corresponding translation key. ```jsx import React from 'react'; import { Trans } from 'react-i18next'; export default function MyComponent () { return

Welcome to React

} // the translation in this case should be "<0>Welcome to React": "<0>Welcome to React and react-i18next" ``` -------------------------------- ### Basic i18n setup with react-i18next (TypeScript) Source: https://react.i18next.com/getting-started.md Same as the JavaScript version but written in TypeScript. The translation key is accessed using the syntax `t($ => $['Welcome to React'])` instead of `t('Welcome to React')`. ```tsx import React from "react"; import { createRoot } from 'react-dom/client'; import i18n from "i18next"; import { useTranslation, initReactI18next } from "react-i18next"; i18n .use(initReactI18next) // passes i18n down to react-i18next .init({ // the translations // (tip move them in a JSON file and import them, // or even better, manage them via a UI: https://react.i18next.com/guides/multiple-translation-files#manage-your-translations-with-a-management-gui) resources: { en: { translation: { "Welcome to React": "Welcome to React and react-i18next" } } }, lng: "en", // if you're using a language detector, do not define the lng option fallbackLng: "en", interpolation: { escapeValue: false // react already safes from xss => https://www.i18next.com/translation-function/interpolation#unescape } }); function App() { const { t } = useTranslation(); return

{t($ => $['Welcome to React'])}

; } // append app to dom const root = createRoot(document.getElementById('root')); root.render( ); ``` -------------------------------- ### Babel macro setup commands for create-react-app Source: https://react.i18next.com/misc/using-with-icu-format.md Commands to set up babel-plugin-macros: create a new app with npx create-react-app, or upgrade an existing app with yarn upgrade react-scripts@2. The macro plugin is included in react-scripts v2. ```shell $ # Create a new application $ npx create-react-app $ # Upgrade an existing application $ yarn upgrade react-scripts@2 ``` -------------------------------- ### Using I18nextProvider with i18n and defaultNS Source: https://react.i18next.com/latest/i18nextprovider.md Wrap your App with I18nextProvider, passing the i18n instance and optionally defaultNS to manage default namespaces. Required for multiple i18next instances or SSR setups. ```jsx import { I18nextProvider } from 'react-i18next'; import i18n from './i18n'; import App from './App'; ``` -------------------------------- ### JSX tree before translation Source: https://react.i18next.com/getting-started.md Example of React code before using the Trans component, showing hardcoded content with HTML formatting and components. ```jsx
Hello {name}, you have {count} unread message(s). Go to messages.
``` -------------------------------- ### Change language with i18n instance Source: https://react.i18next.com/latest/translation-render-prop.md Example of using the i18n instance obtained from the Translation render prop to change the language. ```javascript i18n.changeLanguage('en-US'); ``` -------------------------------- ### Example test using this configuration Source: https://react.i18next.com/misc/testing.md This test renders a component wrapped in I18nextProvider with the test i18n instance, and uses redux-mock-store to simulate a store. It verifies that clicking a sort button dispatches the SORT_TABLE action. ```javascript import React from 'react'; import { Provider } from 'react-redux'; import { render, fireEvent } from '@testing-library/react'; import { I18nextProvider } from 'react-i18next'; import configureStore from 'redux-mock-store'; import ContactTable from './ContactTable'; import actionTypes from '../constants'; import i18n from '../i18nForTests'; const mockStore = configureStore([]); const store = mockStore({ contacts: [ ] }); it('dispatches SORT_TABLE', () => { const { container } = render( ); fireEvent.click(container.querySelector('.sort')); const actions = store.getActions(); expect(actions).toEqual([{ type: actionTypes.SORT_TABLE }]); }); ``` -------------------------------- ### JSX tree after using Trans component (TypeScript) Source: https://react.i18next.com/getting-started.md TypeScript version of the Trans component example, using a selector callback for the title attribute. ```tsx Hello $.nameTitle)}>{{name}}, you have {{count}} unread message. Go to messages. ``` -------------------------------- ### Translation string with numbered placeholders Source: https://react.i18next.com/guides/the-drawbacks-of-other-i18n-solutions.md Example of a translation string that keeps the mixed JSX as one sentence using numbered placeholders. This is the format that the Trans component can handle. ```text Hello <1>{name}, you have <3>{count} unread message(s). ``` -------------------------------- ### Trans component example Source: https://react.i18next.com/latest/using-with-hooks.md Use the Trans component to translate a JSX tree, allowing translation of text containing components like . The translation key includes numbered placeholders. ```jsx import React from 'react'; import { Trans } from 'react-i18next'; export default function MyComponent () { return Welcome to React } // the translation in this case should be "Welcome to <1>React": "Welcome to <1>React and react-i18next" ``` -------------------------------- ### More samples of babel macro Trans usage Source: https://react.i18next.com/misc/using-with-icu-format.md Examples of using the Trans macro for basic interpolation, interpolation with components, number formatting, date formatting, and a link with number formatting. Each sample shows a JSX usage and a defaults variant for translation keys. ```jsx // basic interpolation Welcome, { name }! // interpolation and components Welcome, { name }! // number formatting Trainers: { trainersCount, number } Trainers: { trainersCount, number }! // date formatting Caught on { catchDate, date, short } Caught on { catchDate, date, short }! You have { unread, number } messages ``` -------------------------------- ### Basic i18n setup with react-i18next (JavaScript) Source: https://react.i18next.com/getting-started.md Initializes i18next with react-i18next, defines English translations, and uses the useTranslation hook in a React component. The lng option is set to 'en' and fallbackLng to 'en'. Interpolation escaping is disabled because React already handles XSS safety. ```jsx import React from "react"; import { createRoot } from 'react-dom/client'; import i18n from "i18next"; import { useTranslation, initReactI18next } from "react-i18next"; i18n .use(initReactI18next) // passes i18n down to react-i18next .init({ // the translations // (tip move them in a JSON file and import them, // or even better, manage them via a UI: https://react.i18next.com/guides/multiple-translation-files#manage-your-translations-with-a-management-gui) resources: { en: { translation: { "Welcome to React": "Welcome to React and react-i18next" } } }, lng: "en", // if you're using a language detector, do not define the lng option fallbackLng: "en", interpolation: { escapeValue: false // react already safes from xss => https://www.i18next.com/translation-function/interpolation#unescape } }); function App() { const { t } = useTranslation(); return

{t('Welcome to React')}

; } // append app to dom const root = createRoot(document.getElementById('root')); root.render( ); ``` -------------------------------- ### Using babel macro Trans for ICU and Trans Source: https://react.i18next.com/misc/using-with-icu-format.md Example of using the Trans macro from 'react-i18next/icu.macro'. The macro adds the needed import for IcuTrans and generates the correct component for you. The translation string is output to console if debug is true or submitted via saveMissing, if enabled. ```javascript import { Trans } from 'react-i18next/icu.macro'; const user = 'John Doe'; We invited {user}. ``` -------------------------------- ### JSX with mixed nodes for translation Source: https://react.i18next.com/guides/the-drawbacks-of-other-i18n-solutions.md Example of JSX content that combines text and components. It illustrates the challenge of translating mixed JSX nodes in a single sentence, which most frameworks require splitting into multiple translation strings. ```javascript

Hello {name}, you have {count} unread message(s).

``` -------------------------------- ### Spy on t function with jest.fn (TypeScript) Source: https://react.i18next.com/misc/testing.md TypeScript version of the spy example, using a typed t function with interpolation. ```tsx // implementation import React from 'react'; import { useTranslation } from 'react-i18next'; export default function CustomComponent() { const { t } = useTranslation(); return
{t($ => $.some.key, { some: 'variable' })}
; } // test import React from 'react'; import { render, screen } from '@testing-library/react'; import UseTranslationWithInterpolation from './UseTranslationWithInterpolation'; import { useTranslation } from 'react-i18next'; jest.mock('react-i18next', () => ({ useTranslation: jest.fn(), })); ``` -------------------------------- ### Configure i18next instance with backend, language detector, and initReactI18next Source: https://react.i18next.com/latest/i18next-instance.md Initializes the i18next instance with a backend for loading translations from the server, a language detector, and binds react-i18next. Sets fallback language to 'en', enables debug mode, and disables interpolation escaping for React. Includes commented-out optional react-specific options. ```javascript import i18n from 'i18next'; import Backend from 'i18next-http-backend'; import LanguageDetector from 'i18next-browser-languagedetector'; import { initReactI18next } from 'react-i18next'; i18n .use(Backend) .use(LanguageDetector) .use(initReactI18next) // bind react-i18next to the instance .init({ fallbackLng: 'en', debug: true, interpolation: { escapeValue: false, // not needed for react!! }, // react i18next special options (optional) // override if needed - omit if ok with defaults /* react: { bindI18n: 'languageChanged', bindI18nStore: '', transEmptyNodeValue: '', transSupportBasicHtmlNodes: true, transKeepBasicHtmlNodesFor: ['br', 'strong', 'i'], useSuspense: true, } */ }); export default i18n; ``` -------------------------------- ### Overriding component props with listed components (v11.5.0) - JSX example Source: https://react.i18next.com/latest/trans-component.md Alternative method using array for components prop. ```javascript ]} /> ``` -------------------------------- ### withTranslation HOC in TypeScript Source: https://react.i18next.com/latest/using-with-hooks.md TypeScript version of the withTranslation HOC example. Uses the t function with a callback syntax for type-safe translation keys. ```tsx import React, { Component, Suspense } from 'react'; import { withTranslation } from 'react-i18next'; class LegacyComponentClass extends Component { render() { const { t } = this.props; return (

{t($ => $['Welcome to React'])}

) } } const MyComponent = withTranslation()(LegacyComponentClass) // i18n translations might still be loaded by the http backend // use react's Suspense export default function App() { return ( ); } ``` -------------------------------- ### Configure i18next in i18n.js with hooks Source: https://react.i18next.com/latest/using-with-hooks.md Create i18n.js beside index.js to initialize i18next with backend, language detector, and react-i18next. Sets fallback language to 'en' and disables escaping for React. ```javascript import i18n from 'i18next'; import { initReactI18next } from 'react-i18next'; import Backend from 'i18next-http-backend'; import LanguageDetector from 'i18next-browser-languagedetector'; // don't want to use this? // have a look at the Quick start guide // for passing in lng and translations on init i18n // load translation using http -> see /public/locales (i.e. https://github.com/i18next/react-i18next/tree/master/example/react/public/locales) // learn more: https://github.com/i18next/i18next-http-backend // want your translations to be loaded from a professional CDN? => https://github.com/locize/react-tutorial#step-2---use-the-locize-cdn .use(Backend) // detect user language // learn more: https://github.com/i18next/i18next-browser-languageDetector .use(LanguageDetector) // pass the i18n instance to react-i18next. .use(initReactI18next) // init i18next // for all options read: https://www.i18next.com/overview/configuration-options .init({ fallbackLng: 'en', debug: true, interpolation: { escapeValue: false, // not needed for react as it escapes by default } }); export default i18n; ``` -------------------------------- ### useTranslation hook in TypeScript Source: https://react.i18next.com/latest/using-with-hooks.md TypeScript version of the useTranslation hook example. Uses the t function with a callback syntax for type-safe translation keys. ```tsx import React, { Suspense } from 'react'; import { useTranslation } from 'react-i18next'; function MyComponent() { const { t, i18n } = useTranslation(); return

{t($ => $['Welcome to React'])}

} // i18n translations might still be loaded by the http backend // use react's Suspense export default function App() { return ( ); } ``` -------------------------------- ### After: Using Trans component (JavaScript) Source: https://react.i18next.com/latest/trans-component.md Shows how to replace the untranslated code with the Trans component in JavaScript, using the i18nKey and count props. ```jsx import { Trans } from 'react-i18next'; function MyComponent({ person, messages }) { const { name } = person; const count = messages.length; return ( Hello {{name}}, you have {{count}} unread message. Go to messages. ); } ``` -------------------------------- ### Using i18next directly in React (JavaScript and TypeScript) Source: https://react.i18next.com/guides/the-drawbacks-of-other-i18n-solutions.md Shows how to use the i18next framework directly in a React component. The JavaScript version uses i18n.t('welcome') while the TypeScript version uses i18n.t($ => $.welcome). Both initialize i18next with a translation catalog and render a simple welcome message. ```jsx import React, { Component } from "react"; import { createRoot } from 'react-dom/client'; import i18n from "i18next"; // translation catalog const resources = { en: { translation: { "welcome": "Welcome to React and react-i18next" } } }; // initialize i18next with catalog and language to use i18n.init({ resources, lng: "en" }); class App extends Component { render() { return

{i18n.t('welcome')}

; } } // append app to dom const root = createRoot(document.getElementById('root')); root.render( ); ``` ```tsx import React, { Component } from "react"; import { createRoot } from 'react-dom/client'; import i18n from "i18next"; // translation catalog const resources = { en: { translation: { "welcome": "Welcome to React and react-i18next" } } }; // initialize i18next with catalog and language to use i18n.init({ resources, lng: "en" }); class App extends Component { render() { return

{i18n.t($ => $.welcome)}

; } } // append app to dom const root = createRoot(document.getElementById('root')); root.render( ); ``` -------------------------------- ### Overriding component props with Trans (v11.5.0) - JSX example Source: https://react.i18next.com/latest/trans-component.md Uses Trans with custom component and href to override based on active language. ```javascript }} /> ``` -------------------------------- ### Create i18n.js configuration Source: https://react.i18next.com/guides/quick-start.md Initializes i18next with react-i18next, defines translation resources for English and French, and sets the default language to 'en'. The file can be named anything as long as it is imported correctly. ```javascript import i18n from "i18next"; import { initReactI18next } from "react-i18next"; // the translations // (tip move them in a JSON file and import them, // or even better, manage them separated from your code: https://react.i18next.com/guides/multiple-translation-files) const resources = { en: { translation: { "Welcome to React": "Welcome to React and react-i18next" } }, fr: { translation: { "Welcome to React": "Bienvenue à React et react-i18next" } } }; i18n .use(initReactI18next) // passes i18n down to react-i18next .init({ resources, lng: "en", // language to use, more information here: https://www.i18next.com/overview/configuration-options#languages-namespaces-resources // you can use the i18n.changeLanguage function to change the language manually: https://www.i18next.com/overview/api#changelanguage // if you're using a language detector, do not define the lng option interpolation: { escapeValue: false // react already safes from xss } }); export default i18n; ``` -------------------------------- ### useTranslation hook in JavaScript Source: https://react.i18next.com/guides/quick-start.md Use the useTranslation hook in a functional component to get the t function and i18n instance. The t function is the main translation function in i18next. ```jsx import React from 'react'; // the hook import { useTranslation } from 'react-i18next'; function MyComponent () { const { t, i18n } = useTranslation(); return

{t('Welcome to React')}

} ``` -------------------------------- ### Use useTranslation hook in functional component Source: https://react.i18next.com/latest/migrating-v9-to-v10.md Shows the new hook-based API in v10 for functional components. Use `useTranslation` to get the `t` function and the `i18n` instance. ```jsx import React from 'react'; import { useTranslation } from 'react-i18next'; export function MyComponent() { const [t, i18n] = useTranslation(); return

{t('my translated text')}

} ``` -------------------------------- ### Translation file sample Source: https://react.i18next.com/latest/using-with-hooks.md Sample content for a translation file located at public/locales//translation.json. It contains a title and a nested description object. ```json { "title": "Welcome to react using react-i18next", "description": { "part1": "To get started, edit <1>src/App.js and save to reload.", "part2": "Switch language between english and german using buttons above." } } ``` -------------------------------- ### Spy on t function with jest.fn (JavaScript) Source: https://react.i18next.com/misc/testing.md Spy on the t function using jest.fn to verify calls and arguments in tests. This example shows a component using useTranslation with interpolation and its test. ```jsx // implementation import React from 'react'; import { useTranslation } from 'react-i18next'; export default function CustomComponent() { const { t } = useTranslation(); return
{t('some.key', { some: 'variable' })}
; } // test import React from 'react'; import { render, screen } from '@testing-library/react'; import UseTranslationWithInterpolation from './UseTranslationWithInterpolation'; import { useTranslation } from 'react-i18next'; jest.mock('react-i18next', () => ({ useTranslation: jest.fn(), })); it('test render', () => { const useTranslationSpy = useTranslation; const tSpy = jest.fn((str) => str); useTranslationSpy.mockReturnValue({ t: tSpy, i18n: { changeLanguage: () => new Promise(() => {}), }, }); render(); expect(screen.getByText('some.key')).toBeInTheDocument(); // If you want you can also check how the t function has been called, // but basically this is testing your mock and not the actual code. expect(tSpy).toHaveBeenCalledTimes(1); expect(tSpy).toHaveBeenLastCalledWith('some.key', { some: 'variable' }); }); ``` -------------------------------- ### After: Using Trans component (TypeScript) Source: https://react.i18next.com/latest/trans-component.md Shows how to replace the untranslated code with the Trans component in TypeScript, using the i18nKey and count props. ```tsx import { Trans } from 'react-i18next'; function MyComponent({ person, messages }) { const { name } = person; const count = messages.length; return ( Hello $.nameTitle)}>{{name}}, you have {{count}} unread message. Go to messages. ); } ``` -------------------------------- ### After: Using Trans component with semantic keys (JavaScript) Source: https://react.i18next.com/ Shows the updated JSX using the Trans component with semantic i18n keys and interpolation for name and count. ```jsx ...
{t('simpleContent')}
Hello {{name}}, you have {{count}} unread message(s). Go to messages. ... ``` -------------------------------- ### Manual jest mock for react-i18next Source: https://react.i18next.com/misc/testing.md Create a manual mock in __mocks__/react-i18next.js that covers useTranslation, withTranslation, and Trans, so components mixing all three render keys and children as plain text. ```jsx const React = require('react'); const reactI18next = require('react-i18next'); const useMock = [(k) => k, { changeLanguage: () => new Promise(() => {}) }]; useMock.t = (k) => k; useMock.i18n = { changeLanguage: () => new Promise(() => {}) }; module.exports = { ...reactI18next, withTranslation: () => (Component) => (props) => k} {...props} />, Trans: ({ children, i18nKey }) => children ?? i18nKey, useTranslation: () => useMock, }; ``` -------------------------------- ### Access translation from default namespace with i18next.t (TypeScript) Source: https://react.i18next.com/guides/multiple-translation-files.md Accesses a translation key from the default namespace using i18next.t with a type-safe callback syntax. This is the TypeScript variant of the JavaScript example. ```tsx i18next.t($ => $.look.deep); ``` -------------------------------- ### Translation strings in en.json Source: https://react.i18next.com/latest/icu-trans-component.md The translation JSON needed for the IcuTrans example. It contains the nameTitle string and the pluralized userMessagesUnread keys (one/other) with ICU placeholders matching the defaultTranslation format. ```json "nameTitle": "This is your name", "userMessagesUnread_one": "Hello <1>{{name}}, you have {{count}} unread message. <5>Go to message.", "userMessagesUnread_other": "Hello <1>{{name}}, you have {{count}} unread messages. <5>Go to messages.", ``` -------------------------------- ### TypeScript error for non-string in select interpolation Source: https://react.i18next.com/misc/using-with-icu-format.md Demonstrates that the `select` tagged template will cause a TypeScript error if a non-string is interpolated. The example shows a number variable causing a type error. ```jsx import { Trans, select } from "react-i18next/icu.macro"; // type error below - awesomePercentage must be a number const notAString = 100; {select`${notAString} oops { you have to pass in a string } other { oh well }`} ``` -------------------------------- ### Format a number with a skeleton using ICU macro Source: https://react.i18next.com/misc/using-with-icu-format.md Shows how to use a number skeleton (e.g., `::percent`) with the `number` tagged template. The resulting translation string is `It's awesome {awesomePercentage, number, ::percent} of the time`. ```jsx import { Trans, number } from "react-i18next/icu.macro"; const awesomePercentage = 100; It's awesome {number`${awesomePercentage}, ::percent`} of the time ``` -------------------------------- ### withTranslation HOC usage in JavaScript Source: https://react.i18next.com/latest/withtranslation-hoc.md Use withTranslation to inject t and i18n into a functional component. The HOC wraps the component and provides the t function for translations. This example shows the basic JavaScript usage. ```jsx import React from 'react'; import { withTranslation } from 'react-i18next'; function MyComponent({ t, i18n }) { return

{t('my translated text')}

} export default withTranslation()(MyComponent); ``` -------------------------------- ### After: IcuTrans component in TypeScript Source: https://react.i18next.com/latest/icu-trans-component.md TypeScript version of the IcuTrans example, identical to JavaScript except for the title prop uses t(($) => $.nameTitle) instead of t('nameTitle'). Demonstrates typing support for the content array. ```tsx import { IcuTrans } from 'react-i18next'; function MyComponent({ person, messages }) { const { name } = person; const count = messages.length; return ( fallbacks to defaults if not provided defaultTranslation="hello <0>{{name}}, you have {{count}} unread message. <1>Go to messages." values={{ name, count }} content={[ { type: "strong", props: { title: t(($) => $.nameTitle), }, }, { type: Link, props: { to: "/msgs", }, }, ]} /> ); } ```