CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-react-i18next

React integration for i18next internationalization framework with hooks, components, and SSR support

Pending
Overview
Eval results
Files

components.mddocs/

React Components

React i18next provides specialized components for rendering translations with HTML interpolation, managing i18next context, and render prop patterns.

Capabilities

Trans Component

Component for rendering translations that contain HTML elements, React components, or complex interpolation. Parses translation strings with numbered placeholders and maps them to React elements.

/**
 * Component for complex translations with HTML/React element interpolation
 * @param props - Trans component properties including i18nKey and interpolation options
 */
function Trans<
  Key extends ParseKeys<Ns, TOpt, KPrefix>,
  Ns extends Namespace = TypeOptions['defaultNS'],
  KPrefix = undefined,
  TContext extends string | undefined = undefined,
  TOpt extends TOptions & { context?: TContext } = { context: TContext },
  E = React.HTMLProps<HTMLDivElement>
>(props: TransProps<Key, Ns, KPrefix, TContext, TOpt, E>): React.ReactElement;

interface TransProps<Key, Ns, KPrefix, TContext, TOpt, E> extends E {
  /** Template content with numbered placeholders */
  children?: TransChild | readonly TransChild[];
  /** React elements mapped to numbered placeholders */
  components?: readonly React.ReactElement[] | { readonly [tagName: string]: React.ReactElement };
  /** Count for pluralization */
  count?: number;
  /** Translation context for contextual variations */
  context?: TContext;
  /** Default translation if key is missing */
  defaults?: string;
  /** Custom i18next instance */
  i18n?: i18n;
  /** Translation key or array of keys */
  i18nKey?: Key | Key[];
  /** Namespace for the translation */
  ns?: Ns;
  /** Parent element type or component */
  parent?: string | React.ComponentType<any> | null;
  /** Additional translation options */
  tOptions?: TOpt;
  /** Values for interpolation */
  values?: {};
  /** Control HTML entity unescaping */
  shouldUnescape?: boolean;
  /** Override translation function */
  t?: TFunction<Ns, KPrefix>;
}

type TransChild = React.ReactNode | Record<string, unknown>;

Usage Examples:

import { Trans } from "react-i18next";

// Basic HTML interpolation
// Translation: "Go <1>there</1>."
function Navigation() {
  return (
    <Trans i18nKey="navigation.goThere">
      Go <a href="/somewhere">there</a>.
    </Trans>
  );
}

// Component mapping with array
// Translation: "Hello <1><0>{{name}}</0></1>, you have <3>{{count}}</3> message."
function WelcomeMessage({ name, count }) {
  return (
    <Trans 
      i18nKey="welcome.message"
      values={{ name, count }}
      components={[
        <strong />,           // <0>
        <span className="user" />, // <1>
        null,                 // <2> (unused)
        <b />                 // <3>
      ]}
    />
  );
}

// Component mapping with object
// Translation: "Visit our <Link>homepage</Link> or <Button>contact us</Button>."
function CallToAction() {
  return (
    <Trans
      i18nKey="cta.message"
      components={{
        Link: <a href="/" />,
        Button: <button onClick={handleContact} />
      }}
    />
  );
}

// With pluralization
// Translations: "You have {{count}} item" / "You have {{count}} items"  
function ItemStatus({ count }) {
  return (
    <Trans i18nKey="itemCount" count={count} values={{ count }}>
      You have <strong>{{count}}</strong> item
    </Trans>
  );
}

// With context
// Translations: "Go <1>there</1>." / "Go <1>home</1>." (context: "home")
function ContextualLink({ isHome }) {
  return (
    <Trans 
      i18nKey="navigation.go"
      context={isHome ? "home" : undefined}
    >
      Go <a href={isHome ? "/" : "/somewhere"}>there</a>.
    </Trans>
  );
}

// Custom parent element
function FormattedTranslation() {
  return (
    <Trans 
      i18nKey="formatted.text"
      parent="section"
      className="translation-section"
    >
      This content will be wrapped in a section element.
    </Trans>
  );
}

TransWithoutContext Component

Standalone Trans component that doesn't rely on React context, requiring explicit i18next instance.

/**
 * Trans component without context dependency - requires explicit i18next instance
 * Available as separate import: react-i18next/TransWithoutContext
 */
const TransWithoutContext: typeof Trans;

Usage Examples:

import { Trans } from "react-i18next/TransWithoutContext";
import i18next from "i18next";

// Explicit i18next instance required
function StandaloneTranslation() {
  return (
    <Trans 
      i18n={i18next}
      i18nKey="standalone.message"
    >
      This works without <strong>context</strong>.
    </Trans>
  );
}

I18nextProvider Component

React context provider that supplies i18next instance and configuration to child components.

/**
 * React context provider for i18next instance and configuration
 * @param props - Provider props with i18next instance and optional default namespace
 */
function I18nextProvider(props: I18nextProviderProps): React.FunctionComponent;

interface I18nextProviderProps {
  /** Child components that will have access to i18next context */
  children?: React.ReactNode;
  /** i18next instance to provide to children (required) */  
  i18n: i18n;
  /** Default namespace(s) for child components */
  defaultNS?: string | string[];
}

Usage Examples:

import { I18nextProvider, useTranslation } from "react-i18next";
import i18next from "i18next";

// Basic provider setup
function App() {
  return (
    <I18nextProvider i18n={i18next}>
      <HomePage />
      <UserProfile />
    </I18nextProvider>
  );
}

// With default namespace
function DashboardApp() {
  return (
    <I18nextProvider i18n={i18next} defaultNS="dashboard">
      <DashboardContent />
    </I18nextProvider>
  );
}

// Multiple providers for different sections
function MultiSectionApp() {
  return (
    <div>
      <I18nextProvider i18n={adminI18n} defaultNS="admin">
        <AdminPanel />
      </I18nextProvider>
      
      <I18nextProvider i18n={userI18n} defaultNS="user">
        <UserSection />
      </I18nextProvider>
    </div>
  );
}

function HomePage() {
  const { t } = useTranslation(); // Uses i18n from provider
  return <h1>{t('welcome')}</h1>;
}

Translation Component (Render Prop)

Render prop component that provides translation function and related data to child render functions.

/**
 * Render prop component providing translation function and i18next data
 * @param props - Component props with render function and configuration
 */
function Translation<
  Ns extends FlatNamespace | $Tuple<FlatNamespace> | undefined = undefined,
  KPrefix extends KeyPrefix<FallbackNs<Ns>> = undefined
>(props: TranslationProps<Ns, KPrefix>): React.ReactNode;

interface TranslationProps<Ns, KPrefix> {
  /** Render function receiving translation data */
  children: (
    t: TFunction<FallbackNs<Ns>, KPrefix>,
    options: {
      i18n: i18n;
      lng: string;
    },
    ready: boolean
  ) => React.ReactNode;
  /** Namespace(s) for translations */
  ns?: Ns;
  /** Custom i18next instance */
  i18n?: i18n;
  /** Enable React Suspense */
  useSuspense?: boolean;
  /** Key prefix for translations */
  keyPrefix?: KPrefix;
  /** Namespace resolution mode */
  nsMode?: 'fallback' | 'default';
}

Usage Examples:

import { Translation } from "react-i18next";

// Basic render prop usage
function UserGreeting({ username }) {
  return (
    <Translation>
      {(t, { i18n, lng }, ready) => {
        if (!ready) return <div>Loading...</div>;
        
        return (
          <div>
            <h1>{t('greeting', { name: username })}</h1>
            <p>Current language: {lng}</p>
            <button onClick={() => i18n.changeLanguage('es')}>
              {t('switchToSpanish')}
            </button>
          </div>
        );
      }}
    </Translation>
  );
}

// With namespace and key prefix  
function SettingsPanel() {
  return (
    <Translation ns="settings" keyPrefix="panel">
      {(t, { i18n }) => (
        <div className="settings-panel">
          <h2>{t('title')}</h2> {/* settings:panel.title */}
          <button onClick={() => i18n.reloadResources()}>
            {t('refresh')} {/* settings:panel.refresh */}
          </button>
        </div>
      )}
    </Translation>
  );
}

// Error handling and loading states
function StatusAwareComponent() {
  return (
    <Translation ns={['main', 'errors']}>
      {(t, { i18n, lng }, ready) => {
        if (!ready) {
          return <div className="loading">{t('loading')}</div>;
        }

        return (
          <div>
            <h1>{t('main:welcome')}</h1>
            {i18n.isInitialized ? (
              <p>{t('main:ready', { language: lng })}</p>
            ) : (
              <p>{t('errors:notInitialized')}</p>
            )}
          </div>
        );
      }}
    </Translation>
  );
}

React Context

/**
 * React context providing i18next instance and configuration
 */
const I18nContext: React.Context<{ 
  i18n: i18n;
  defaultNS?: string | string[];
}>;

Usage Examples:

import { useContext } from "react";
import { I18nContext } from "react-i18next";

// Direct context access
function DebugComponent() {
  const { i18n, defaultNS } = useContext(I18nContext) || {};
  
  return (
    <div>
      <p>Language: {i18n?.language}</p>
      <p>Default NS: {defaultNS}</p>
      <p>Initialized: {i18n?.isInitialized ? 'Yes' : 'No'}</p>
    </div>
  );
}

Component Behavior

Trans Component Parsing

The Trans component parses translation strings using numbered placeholders:

  • <0> maps to first element in components array or components[0]
  • <1> maps to second element in components array or components[1]
  • Self-closing tags: <0/> renders as-is without children
  • Nested elements: <0><1>content</1></0> creates nested structure

HTML Support

Trans component supports basic HTML elements by default:

  • Preserves: <br>, <strong>, <i>, <p> (configurable)
  • Escapes: Other HTML elements for security
  • Control via transSupportBasicHtmlNodes and transKeepBasicHtmlNodesFor options

Error Handling

Components handle common error scenarios:

  • Missing translations: Shows translation key or defaults
  • Invalid component mapping: Renders placeholder or children as-is
  • Context unavailable: Falls back to global i18next instance
  • Type errors: Provides TypeScript warnings during development

Install with Tessl CLI

npx tessl i tessl/npm-react-i18next

docs

components.md

hocs.md

hooks.md

icu-macro.md

index.md

ssr.md

tile.json