CodeSampleX

サンプル

react 18.2.0: useId

検証済みサンプル — npm react 18.2.0: useId. node 22 · linux alpine/x64 · docker で contract を実行し、成功しました: React.useId throws a TypeError when invoked outside of a…

sha256:65284c80e93d911785e302379b4a89902124c7fc6e94011549890211d960f809

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
1
ビルドした署名鍵
1
宣言された環境 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

検証実行環境

環境 コントラクト ステージ 実行日
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-27

ケース

HOW
ゴール
verify React.useId in pkg:npm/react@18.2.0
パッケージ
シンボル
  • React.useId
環境
node 22.23.2
作成日
2026-08-27T10:05:29Z

コントラクト

  1. React.useId throws a TypeError when invoked outside of a React component render context.
  2. React.useId returns a non-empty string identifier formatted with colons when invoked within a rendered component.
  3. Multiple calls to React.useId within the same component produce distinct unique identifiers.
  4. Separate instances of a component using React.useId produce distinct identifiers across the rendered tree.
  5. React.useId generated identifiers can be composed with suffixes to link form labels and aria-describedby hints.

ファイル

  • PROMPT.md
  • csx.json
  • index.js
  • package-lock.json
  • package.json
  • spec.json
  • test/contract.cjs

ソースアーティファクトをダウンロード (tar.gz)

ソース

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 React.useId in pkg:npm/react@18.2.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/react@18.2.0
Demonstrate these symbols/APIs:
  - React.useId

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:ac217d1b747da3d9be21dff476c067c8d5077e59efa1ec2866a865ba5022c672","constraints":{"executionContext":"node"},"contract":["React.useId throws a TypeError when invoked outside of a React component render context.","React.useId returns a non-empty string identifier formatted with colons when invoked within a rendered component.","Multiple calls to React.useId within the same component produce distinct unique identifiers.","Separate instances of a component using React.useId produce distinct identifiers across the rendered tree.","React.useId generated identifiers can be composed with suffixes to link form labels and aria-describedby hints."],"goal":"verify React.useId in pkg:npm/react@18.2.0","kind":"HOW","packages":["pkg:npm/react@18.2.0"],"schemaVersion":1,"symbols":["React.useId"]},"contractCommand":["node","test/contract.cjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/react@18.2.0"],"schemaVersion":1,"subject":"pkg:npm/react@18.2.0","symbols":["React.useId"],"verifierAdapter":"node-typescript@1"}
index.js
const React = require('react');
const ReactDOMServer = require('react-dom/server');

/**
 * Custom form field component that uses React.useId to generate unique IDs
 * for binding label htmlFor, input id, and aria-describedby hint.
 */
function FormField({ label, hint, defaultValue = '' }) {
  const id = React.useId();
  const inputId = `${id}-input`;
  const hintId = `${id}-hint`;

  return React.createElement(
    'div',
    { className: 'form-field' },
    React.createElement('label', { htmlFor: inputId }, label),
    React.createElement('input', {
      id: inputId,
      'aria-describedby': hint ? hintId : undefined,
      defaultValue,
    }),
    hint ? React.createElement('span', { id: hintId }, hint) : null
  );
}

/**
 * Component that calls React.useId multiple times to generate distinct field IDs.
 */
function MultiIdComponent() {
  const primaryId = React.useId();
  const secondaryId = React.useId();

  return React.createElement(
    'div',
    { 'data-primary': primaryId, 'data-secondary': secondaryId },
    React.createElement('span', { id: primaryId }, 'Primary'),
    React.createElement('span', { id: secondaryId }, 'Secondary')
  );
}

/**
 * Helper to render any React element to HTML string.
 */
function renderComponent(element) {
  return ReactDOMServer.renderToString(element);
}

/**
 * Calls React.useId directly outside of React rendering context.
 * Used to verify invalid hook invocation behavior.
 */
function callUseIdDirectly() {
  return React.useId();
}

module.exports = {
  FormField,
  MultiIdComponent,
  renderComponent,
  callUseIdDirectly,
};
package-lock.json
{
  "name": "sample-react-use-id",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-react-use-id",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "react": "18.2.0",
        "react-dom": "18.2.0"
      }
    },
    "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.2.0",
      "resolved": "https://registry.npmjs.org/react/-/react-18.2.0.tgz",
      "integrity": "sha512-/3IjMdb2L9QbBdWiW5e3P2/npwMBaU9mHCSCUzNln0ZCYbcfTsGbTJrU/kGemdH2IWmB2ioZ+zkxtmq6g09fGQ==",
      "license": "MIT",
      "dependencies": {
        "loose-envify": "^1.1.0"
      },
      "engines": {
        "node": ">=0.10.0"
      }
    },
    "node_modules/react-dom": {
      "version": "18.2.0",
      "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.2.0.tgz",
      "integrity": "sha512-6IMTriUmvsjHUjNtEDudZfuDQUoWXVxKHhlEGSk81n4YFS+r/Kl99wXiwlVXtPBtJenozv2P+hxDsw9eA7Xo6g==",
      "license": "MIT",
      "dependencies": {
        "loose-envify": "^1.1.0",
        "scheduler": "^0.23.0"
      },
      "peerDependencies": {
        "react": "^18.2.0"
      }
    },
    "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"
      }
    }
  }
}
package.json
{
  "name": "sample-react-use-id",
  "version": "1.0.0",
  "private": true,
  "license": "MIT-0",
  "dependencies": {
    "react": "18.2.0",
    "react-dom": "18.2.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify React.useId in pkg:npm/react@18.2.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/react@18.2.0"
  ],
  "symbols": [
    "React.useId"
  ]
}
test/contract.cjs
const assert = require('node:assert/strict');
const React = require('react');
const {
  FormField,
  MultiIdComponent,
  renderComponent,
  callUseIdDirectly,
} = require('../index.js');

// Contract 1: React.useId throws a TypeError when invoked outside of a React component render context.
assert.throws(
  () => {
    callUseIdDirectly();
  },
  (err) => {
    return (
      err instanceof TypeError &&
      /useId/i.test(err.message)
    );
  },
  'Calling useId outside component render must throw a TypeError related to useId'
);

// Contract 2: React.useId returns a non-empty string identifier formatted with colons when invoked within a rendered component.
{
  let capturedId = null;
  function ProbeComponent() {
    capturedId = React.useId();
    return React.createElement('div', { id: capturedId }, 'Probe');
  }
  const html = renderComponent(React.createElement(ProbeComponent));
  assert.strictEqual(typeof capturedId, 'string', 'useId must return a string');
  assert.ok(capturedId.length > 0, 'useId string must not be empty');
  assert.match(capturedId, /^:r[0-9a-z]+:$/i, 'useId must produce a colon-delimited identifier');
  assert.ok(html.includes(`id="${capturedId}"`), 'Rendered HTML must contain the generated useId');
}

// Contract 3: Multiple calls to React.useId within the same component produce distinct unique identifiers.
{
  let idA = null;
  let idB = null;
  function DualIdComponent() {
    idA = React.useId();
    idB = React.useId();
    return React.createElement('div', null, idA, idB);
  }
  renderComponent(React.createElement(DualIdComponent));
  assert.ok(idA !== null && idB !== null, 'Both IDs must be populated');
  assert.notStrictEqual(idA, idB, 'Multiple useId calls in same component must produce distinct identifiers');
}

// Contract 4: Separate instances of a component using React.useId produce distinct identifiers across the rendered tree.
{
  const parentElement = React.createElement(
    'div',
    null,
    React.createElement(FormField, { label: 'First Name', hint: 'Enter first name' }),
    React.createElement(FormField, { label: 'Last Name', hint: 'Enter last name' })
  );
  const parentHtml = renderComponent(parentElement);
  const matches = [...parentHtml.matchAll(/id="([^"]+)-input"/g)].map(m => m[1]);
  assert.strictEqual(matches.length, 2, 'Must render two FormField inputs');
  assert.notStrictEqual(matches[0], matches[1], 'Each FormField instance must receive a distinct useId');
}

// Contract 5: React.useId generated identifiers can be composed with suffixes to link form labels and aria-describedby hints.
{
  const formHtml = renderComponent(
    React.createElement(FormField, { label: 'Email', hint: 'We will not share your email' })
  );
  const forMatch = formHtml.match(/for="([^"]+)"/);
  const inputMatch = formHtml.match(/id="([^"]+)"/);
  const ariaDescribedByMatch = formHtml.match(/aria-describedby="([^"]+)"/);
  const spanIdMatch = formHtml.match(/<span id="([^"]+)"/);

  assert.ok(forMatch && inputMatch, 'Label for and input id must exist');
  assert.strictEqual(forMatch[1], inputMatch[1], 'Label for attribute must match input id');
  assert.ok(ariaDescribedByMatch && spanIdMatch, 'aria-describedby and hint span id must exist');
  assert.strictEqual(ariaDescribedByMatch[1], spanIdMatch[1], 'aria-describedby must match hint span id');
}

console.log('All React.useId contract tests passed.');

オリジンシーダー

匿名