CodeSampleX

Beispiel

react-i18next 15.7.4: initReactI18next, useTranslation, I18nextProvider

Verifiziertes Beispiel für npm react-i18next 15.7.4: initReactI18next, useTranslation, I18nextProvider. Der Vertrag lief auf node 22 · linux alpine/x64 …

sha256:c75a6edee5b0d4f8b5a355fbf6cb9f1dcd3ebc35538be478504463b69637c68e

Dieses Netzwerk bietet eine Sache: ein Sample, das baut. Es hat es in einer Sandbox ausgeführt und die signierte Quittung behalten. Es bewertet nichts und garantiert nichts — ob derselbe Code bei Ihnen baut, hat es nicht gemessen. Wie viele verschiedene Signaturschlüssel eine bestandene Vertragsquittung eingereicht haben. Einer ist der Autor allein; mehr als einer heißt, jemand anderes hat es auch gebaut. Ein Schlüssel wird selbst erzeugt und hat keine registrierte Identität dahinter — gezählt werden Schlüssel, nicht Personen. MIT-0

Ausführungsbelege

Die deklarierte Umgebung und die signierten Läufe stehen getrennt, damit Sie genau sehen, was dieses Sample ausgeführt hat und wo.

Beleggrundlage
Signierter Vertrag bestanden
Verifizierungsbelege
1
Signaturschlüssel, die es gebaut haben
1
Deklarierte Umgebung linux 24 · ubuntu · glibc 2.39 x64 npm

Umgebungen der Verifizierungsläufe

Umgebung Contract Stufen Lauf
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-21

Fall

HOW
Ziel
verify pkg:npm/react-i18next@15.7.4
Pakete
Symbole
  • initReactI18next
  • useTranslation
  • I18nextProvider
  • Trans
  • Translation
  • withTranslation
Erstellt
2026-08-21T15:15:13Z

Contract

  1. initReactI18next binds i18next instance to react-i18next context and global state
  2. useTranslation hook returns t function resolving translation keys with variable interpolation
  3. useTranslation hook reflects dynamic language changes triggered via i18n instance
  4. I18nextProvider propagates custom i18next instance through React context tree
  5. Trans component interpolates nested JSX elements and variables into translation string
  6. Translation render-prop component resolves translation keys without custom hooks
  7. withTranslation higher-order component injects t and i18n props into wrapped React components

Dateien

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.mjs
  • test/contract.mjs

Quellartefakt herunterladen (tar.gz)

Quelltext

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify pkg:npm/react-i18next@15.7.4
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/react-i18next@15.7.4

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:45ffec0885e0c0ab37b368b8c998947bf6580bc0403e00cc2199943ec9247372","contract":["initReactI18next binds i18next instance to react-i18next context and global state","useTranslation hook returns t function resolving translation keys with variable interpolation","useTranslation hook reflects dynamic language changes triggered via i18n instance","I18nextProvider propagates custom i18next instance through React context tree","Trans component interpolates nested JSX elements and variables into translation string","Translation render-prop component resolves translation keys without custom hooks","withTranslation higher-order component injects t and i18n props into wrapped React components"],"goal":"verify pkg:npm/react-i18next@15.7.4","kind":"HOW","packages":["pkg:npm/react-i18next@15.7.4"],"schemaVersion":1,"symbols":["initReactI18next","useTranslation","I18nextProvider","Trans","Translation","withTranslation"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/react-i18next@15.7.4"],"schemaVersion":1,"subject":"pkg:npm/react-i18next@15.7.4","symbols":["initReactI18next","useTranslation","I18nextProvider","Trans","Translation","withTranslation"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-react-i18next",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-react-i18next",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "i18next": "24.2.3",
        "react": "18.3.1",
        "react-dom": "18.3.1",
        "react-i18next": "15.7.4"
      }
    },
    "node_modules/@babel/runtime": {
      "version": "7.29.7",
      "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz",
      "integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==",
      "license": "MIT",
      "engines": {
        "node": ">=6.9.0"
      }
    },
    "node_modules/html-parse-stringify": {
      "version": "3.1.0",
      "resolved": "https://registry.npmjs.org/html-parse-stringify/-/html-parse-stringify-3.1.0.tgz",
      "integrity": "sha512-E0oAXcELOtsXe+BmpJ2EZyedbldPpriV5vICzEuo6xjC/D1lDukOI7KrpfQGF2Qc4wWEy0nk3bFORS2K5ZAhFQ==",
      "license": "MIT",
      "dependencies": {
        "void-elements": "3.1.0"
      }
    },
    "node_modules/i18next": {
      "version": "24.2.3",
      "resolved": "https://registry.npmjs.org/i18next/-/i18next-24.2.3.tgz",
      "integrity": "sha512-lfbf80OzkocvX7nmZtu7nSTNbrTYR52sLWxPtlXX1zAhVw8WEnFk4puUkCR4B1dNQwbSpEHHHemcZu//7EcB7A==",
      "funding": [
        {
          "type": "individual",
          "url": "https://locize.com"
        },
        {
          "type": "individual",
          "url": "https://locize.com/i18next.html"
        },
        {
          "type": "individual",
          "url": "https://www.i18next.com/how-to/faq#i18next-is-awesome.-how-can-i-support-the-project"
        }
      ],
      "license": "MIT",
      "dependencies": {
        "@babel/runtime": "^7.26.10"
      },
      "peerDependencies": {
        "typescript": "^5"
      },
      "peerDependenciesMeta": {
        "typescript": {
          "optional": true
        }
      }
    },
    "node_modules/js-tokens": {
      "version": "4.0.0",
      "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
      "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
      "license": "MIT"
    },
    "node_modules/loose-envify": {
      "version": "1.4.0",
      "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
      "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
      "license": "MIT",
      "dependencies": {
        "js-tokens": "^3.0.0 || ^4.0.0"
      },
      "bin": {
        "loose-envify": "cli.js"
      }
    },
    "node_modules/react": {
      "version": "18.3.1",
      "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
      "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
      "license": "MIT",
      "dependencies": {
        "loose-envify": "^1.1.0"
      },
      "engines": {
        "node": ">=0.10.0"
      }
    },
    "node_modules/react-dom": {
      "version": "18.3.1",
      "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
      "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
      "license": "MIT",
      "dependencies": {
        "loose-envify": "^1.1.0",
        "scheduler": "^0.23.2"
      },
      "peerDependencies": {
        "react": "^18.3.1"
      }
    },
    "node_modules/react-i18next": {
      "version": "15.7.4",
      "resolved": "https://registry.npmjs.org/react-i18next/-/react-i18next-15.7.4.tgz",
      "integrity": "sha512-nyU8iKNrI5uDJch0z9+Y5XEr34b0wkyYj3Rp+tfbahxtlswxSCjcUL9H0nqXo9IR3/t5Y5PKIA3fx3MfUyR9Xw==",
      "license": "MIT",
      "dependencies": {
        "@babel/runtime": "^7.27.6",
        "html-parse-stringify": "^3.0.1"
      },
      "peerDependencies": {
        "i18next": ">= 23.4.0",
        "react": ">= 16.8.0",
        "typescript": "^5"
      },
      "peerDependenciesMeta": {
        "react-dom": {
          "optional": true
        },
        "react-native": {
          "optional": true
        },
        "typescript": {
          "optional": true
        }
      }
    },
    "node_modules/scheduler": {
      "version": "0.23.2",
      "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",
      "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==",
      "license": "MIT",
      "dependencies": {
        "loose-envify": "^1.1.0"
      }
    },
    "node_modules/void-elements": {
      "version": "3.1.0",
      "resolved": "https://registry.npmjs.org/void-elements/-/void-elements-3.1.0.tgz",
      "integrity": "sha512-Dhxzh5HZuiHQhbvTW9AMetFfBHDMYpo23Uo9btPXgdYP+3T5S+p+jgNy7spra+veYhBP2dCSgxR/i2Y02h5/6w==",
      "license": "MIT",
      "engines": {
        "node": ">=0.10.0"
      }
    }
  }
}
package.json
{
  "name": "sample-react-i18next",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "main": "src/index.mjs",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "i18next": "24.2.3",
    "react": "18.3.1",
    "react-dom": "18.3.1",
    "react-i18next": "15.7.4"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/react-i18next@15.7.4",
  "kind": "HOW",
  "packages": [
    "pkg:npm/react-i18next@15.7.4"
  ]
}
src/index.mjs
import React from 'react';
import i18next from 'i18next';
import {
  initReactI18next,
  useTranslation,
  I18nextProvider,
  Trans,
  Translation,
  withTranslation,
  getI18n,
  setI18n,
} from 'react-i18next';

/**
 * Creates and initializes an i18next instance configured with initReactI18next.
 * @param {object} options - Initialization options for i18next.
 * @returns {Promise<import('i18next').i18n>} Initialized i18next instance.
 */
export async function createI18nInstance(options = {}) {
  const instance = i18next.createInstance();
  await instance.use(initReactI18next).init({
    lng: 'en',
    fallbackLng: 'en',
    interpolation: {
      escapeValue: false,
    },
    ...options,
  });
  return instance;
}

/**
 * Functional component using the useTranslation hook.
 * @param {{ name: string, count?: number }} props
 * @returns {React.ReactElement}
 */
export function GreetingComponent({ name, count }) {
  const { t } = useTranslation();
  return React.createElement(
    'div',
    { className: 'greeting' },
    React.createElement('span', { className: 'message' }, t('greeting', { name })),
    count !== undefined ? React.createElement('span', { className: 'items' }, t('itemCount', { count })) : null
  );
}

/**
 * Component using the Trans component for rich text formatting.
 * @param {{ name: string, i18n?: import('i18next').i18n }} props
 * @returns {React.ReactElement}
 */
export function RichMessageComponent({ name, i18n }) {
  return React.createElement(
    'div',
    { className: 'rich-message' },
    React.createElement(Trans, {
      i18n,
      i18nKey: 'richText',
      values: { name },
      components: {
        strong: React.createElement('strong', null),
        em: React.createElement('em', null),
      },
    })
  );
}

/**
 * Component demonstrating Translation render prop.
 * @returns {React.ReactElement}
 */
export function RenderPropComponent() {
  return React.createElement(
    Translation,
    null,
    (t) => React.createElement('p', { className: 'render-prop' }, t('statusReady'))
  );
}

/**
 * Base component for testing withTranslation HOC.
 */
function BaseHocComponent({ t, title }) {
  return React.createElement('h1', { className: 'hoc-title' }, t('heading', { title }));
}

/**
 * Higher-order component wrapped with withTranslation.
 */
export const WrappedHocComponent = withTranslation()(BaseHocComponent);

export {
  initReactI18next,
  useTranslation,
  I18nextProvider,
  Trans,
  Translation,
  withTranslation,
  getI18n,
  setI18n,
};
test/contract.mjs
import assert from 'node:assert';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import {
  createI18nInstance,
  GreetingComponent,
  RichMessageComponent,
  RenderPropComponent,
  WrappedHocComponent,
  I18nextProvider,
  getI18n,
  initReactI18next,
  useTranslation,
} from '../src/index.mjs';

async function main() {
  const resources = {
    en: {
      translation: {
        greeting: 'Hello, {{name}}!',
        itemCount_one: '{{count}} item',
        itemCount_other: '{{count}} items',
        richText: 'Welcome <strong><em key="1">{{name}}</em></strong> to the platform.',
        statusReady: 'Application is ready.',
        heading: 'Section: {{title}}',
      },
    },
    es: {
      translation: {
        greeting: '¡Hola, {{name}}!',
        itemCount_one: '{{count}} artículo',
        itemCount_other: '{{count}} artículos',
        richText: 'Bienvenido <strong><em key="1">{{name}}</em></strong> a la plataforma.',
        statusReady: 'La aplicación está lista.',
        heading: 'Sección: {{title}}',
      },
    },
  };

  // 1. initReactI18next binds i18next instance to react-i18next context and global state
  const i18n = await createI18nInstance({ resources });
  assert.ok(i18n.isInitialized, 'i18n instance is initialized');
  assert.strictEqual(getI18n(), i18n, 'getI18n() returns the configured i18n instance');

  // 2. useTranslation hook returns t function resolving translation keys with variable interpolation
  const englishGreeting = renderToStaticMarkup(
    React.createElement(
      I18nextProvider,
      { i18n },
      React.createElement(GreetingComponent, { name: 'Alice', count: 1 })
    )
  );
  assert.ok(englishGreeting.includes('Hello, Alice!'), 'renders interpolated greeting in English');
  assert.ok(englishGreeting.includes('1 item'), 'renders singular pluralization form');

  const englishPlural = renderToStaticMarkup(
    React.createElement(
      I18nextProvider,
      { i18n },
      React.createElement(GreetingComponent, { name: 'Alice', count: 5 })
    )
  );
  assert.ok(englishPlural.includes('5 items'), 'renders plural form for count > 1');

  // 3. useTranslation hook reflects dynamic language changes triggered via i18n instance
  await i18n.changeLanguage('es');
  const spanishGreeting = renderToStaticMarkup(
    React.createElement(
      I18nextProvider,
      { i18n },
      React.createElement(GreetingComponent, { name: 'Carlos', count: 3 })
    )
  );
  assert.ok(spanishGreeting.includes('¡Hola, Carlos!'), 'renders greeting in Spanish after language switch');
  assert.ok(spanishGreeting.includes('3 artículos'), 'renders pluralization in Spanish');

  // Switch back to English for remaining tests
  await i18n.changeLanguage('en');

  // 4. I18nextProvider propagates custom i18next instance through React context tree
  const customInstance = await createI18nInstance({
    lng: 'es',
    resources,
  });
  const scopedGreeting = renderToStaticMarkup(
    React.createElement(
      I18nextProvider,
      { i18n: customInstance },
      React.createElement(GreetingComponent, { name: 'Elena' })
    )
  );
  assert.ok(scopedGreeting.includes('¡Hola, Elena!'), 'scoped provider uses custom i18n instance');

  // 5. Trans component interpolates nested JSX elements and variables into translation string
  const richHtml = renderToStaticMarkup(
    React.createElement(
      I18nextProvider,
      { i18n },
      React.createElement(RichMessageComponent, { name: 'DevUser' })
    )
  );
  assert.ok(
    richHtml.includes('<strong><em>DevUser</em></strong>'),
    'Trans component interpolates tags and values properly'
  );

  // 6. Translation render-prop component resolves translation keys without custom hooks
  const renderPropHtml = renderToStaticMarkup(
    React.createElement(
      I18nextProvider,
      { i18n },
      React.createElement(RenderPropComponent, null)
    )
  );
  assert.ok(renderPropHtml.includes('Application is ready.'), 'Translation component resolves message via render prop');

  // 7. withTranslation higher-order component injects t and i18n props into wrapped React components
  const hocHtml = renderToStaticMarkup(
    React.createElement(
      I18nextProvider,
      { i18n },
      React.createElement(WrappedHocComponent, { title: 'Dashboard' })
    )
  );
  assert.ok(hocHtml.includes('Section: Dashboard'), 'withTranslation injects t helper into wrapped component');

  console.log('All react-i18next contract tests passed successfully.');
}

main().catch((err) => {
  console.error('Contract test failed:', err);
  process.exit(1);
});

Ursprungs-Seeder

anonym