CodeSampleX

Пример

react-router-dom 6.30.4: useNavigate

Проверенный пример — npm react-router-dom 6.30.4: useNavigate. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден.

sha256:335af718e8972e828bfbbbaa334943c700ca3eee38edc3853b62cc860d32604d

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. 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-25

Кейс

HOW
Цель
verify react-router-dom.useNavigate in pkg:npm/react-router-dom@6.30.4
Пакеты
Символы
  • react-router-dom.useNavigate
Окружение
node 22.23.2
Создан
2026-08-25T12:33:56Z

Контракт

  1. useNavigate throws invariant error when invoked outside of a Router context.
  2. useNavigate returns a callable navigation function when rendered within a Router provider.
  3. navigate performs push navigation updating the current pathname location and route matches.
  4. navigate supports replace option to replace current history entry instead of pushing a new entry.
  5. navigate passes state object accessible via location.state in target route.
  6. navigate performs delta navigation with negative and positive numbers to traverse history entries.

Файлы

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

Скачать артефакт с исходным кодом (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-router-dom.useNavigate in pkg:npm/react-router-dom@6.30.4
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/react-router-dom@6.30.4
Demonstrate these symbols/APIs:
  - react-router-dom.useNavigate
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:5d8fbf01f11534c3d7c950c5e626e2b8431ef83e89faa84a4cb1301586a3f36a","constraints":{"executionContext":"node"},"contract":["useNavigate throws invariant error when invoked outside of a Router context.","useNavigate returns a callable navigation function when rendered within a Router provider.","navigate performs push navigation updating the current pathname location and route matches.","navigate supports replace option to replace current history entry instead of pushing a new entry.","navigate passes state object accessible via location.state in target route.","navigate performs delta navigation with negative and positive numbers to traverse history entries."],"goal":"verify react-router-dom.useNavigate in pkg:npm/react-router-dom@6.30.4","kind":"HOW","packages":["pkg:npm/react-router-dom@6.30.4"],"schemaVersion":1,"symbols":["react-router-dom.useNavigate"]},"contractCommand":["node","test/contract.js"],"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-router-dom@6.30.4"],"schemaVersion":1,"subject":"pkg:npm/react-router-dom@6.30.4","symbols":["react-router-dom.useNavigate"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-react-router-dom-use-navigate",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-react-router-dom-use-navigate",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "react": "18.3.1",
        "react-dom": "18.3.1",
        "react-router-dom": "6.30.4"
      }
    },
    "node_modules/@remix-run/router": {
      "version": "1.23.3",
      "resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.3.tgz",
      "integrity": "sha512-4An71tdz9X8+3sI4Qqqd2LWd9vS39J7sqd9EU4Scw7TJE/qB10Flv/UuqbPVgfQV9XoK8Np6jNquZitnZq5i+Q==",
      "license": "MIT",
      "engines": {
        "node": ">=14.0.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.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-router": {
      "version": "6.30.4",
      "resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.4.tgz",
      "integrity": "sha512-SVUsDe+DybHM/WmYKIVYhZh1o5Dcuf16yM6WjG02Q9XVFMZIJyHYhwrr6bFBXZkVP6z69kNkMyBCujt8FaFLJA==",
      "license": "MIT",
      "dependencies": {
        "@remix-run/router": "1.23.3"
      },
      "engines": {
        "node": ">=14.0.0"
      },
      "peerDependencies": {
        "react": ">=16.8"
      }
    },
    "node_modules/react-router-dom": {
      "version": "6.30.4",
      "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.4.tgz",
      "integrity": "sha512-q4HvNl+mmDdkS0g+MqiBZNteQJCuimWoOyHMy4T/RQLAn9Z29+E91QXRaxOujeMl2HTzRSS0KFPd7lxX3PjV0Q==",
      "license": "MIT",
      "dependencies": {
        "@remix-run/router": "1.23.3",
        "react-router": "6.30.4"
      },
      "engines": {
        "node": ">=14.0.0"
      },
      "peerDependencies": {
        "react": ">=16.8",
        "react-dom": ">=16.8"
      }
    },
    "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-router-dom-use-navigate",
  "version": "1.0.0",
  "private": true,
  "license": "MIT-0",
  "dependencies": {
    "react": "18.3.1",
    "react-dom": "18.3.1",
    "react-router-dom": "6.30.4"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify react-router-dom.useNavigate in pkg:npm/react-router-dom@6.30.4",
  "kind": "HOW",
  "packages": [
    "pkg:npm/react-router-dom@6.30.4"
  ],
  "symbols": [
    "react-router-dom.useNavigate"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
const React = require('react');
const ReactDOMServer = require('react-dom/server');
const {
  useNavigate,
  useLocation,
  createMemoryRouter,
  MemoryRouter,
  Routes,
  Route,
} = require('react-router-dom');
const { StaticRouter } = require('react-router-dom/server');

/**
 * Component that captures navigate and location hooks for inspection.
 */
function NavigationProbe({ onInspect }) {
  const navigate = useNavigate();
  const location = useLocation();
  if (onInspect) {
    onInspect({ navigate, location });
  }
  return React.createElement(
    'div',
    { 'data-pathname': location.pathname, 'data-search': location.search },
    `Current: ${location.pathname}`
  );
}

/**
 * Component that uses useNavigate for programmatic redirection / button triggers.
 */
function NavigatingComponent({ to, options }) {
  const navigate = useNavigate();
  return React.createElement(
    'button',
    {
      type: 'button',
      onClick: () => navigate(to, options),
    },
    'Go'
  );
}

/**
 * Renders a probe component inside MemoryRouter with specified initial entries.
 *
 * @param {string[]} initialEntries
 * @param {number} [initialIndex=0]
 * @param {Function} [onInspect]
 * @returns {string} Rendered HTML string.
 */
function renderWithMemoryRouter(initialEntries = ['/'], initialIndex = 0, onInspect) {
  const element = React.createElement(
    MemoryRouter,
    { initialEntries, initialIndex },
    React.createElement(NavigationProbe, { onInspect })
  );
  return ReactDOMServer.renderToStaticMarkup(element);
}

/**
 * Renders a probe component inside StaticRouter.
 *
 * @param {string} location
 * @param {Function} [onInspect]
 * @returns {string} Rendered HTML string.
 */
function renderWithStaticRouter(location, onInspect) {
  const element = React.createElement(
    StaticRouter,
    { location },
    React.createElement(NavigationProbe, { onInspect })
  );
  return ReactDOMServer.renderToStaticMarkup(element);
}

/**
 * Attempts to render a component using useNavigate without an enclosing Router.
 * Throws an invariant error.
 */
function renderWithoutRouter() {
  function Standalone() {
    useNavigate();
    return null;
  }
  return ReactDOMServer.renderToStaticMarkup(React.createElement(Standalone));
}

/**
 * Creates an in-memory data router supporting full imperative navigation.
 *
 * @param {Array} routes
 * @param {Object} [options]
 * @returns {Object} Router instance
 */
function createNavigationRouter(routes, options = {}) {
  return createMemoryRouter(routes, {
    initialEntries: options.initialEntries || ['/'],
    initialIndex: options.initialIndex !== undefined ? options.initialIndex : 0,
  });
}

/**
 * Performs push navigation on a router instance.
 *
 * @param {Object} router
 * @param {string|Object} to
 * @param {Object} [options]
 */
function navigateTo(router, to, options) {
  router.navigate(to, options);
}

/**
 * Performs delta navigation (back / forward) on a router instance.
 *
 * @param {Object} router
 * @param {number} delta
 */
function navigateDelta(router, delta) {
  router.navigate(delta);
}

module.exports = {
  useNavigate,
  NavigationProbe,
  NavigatingComponent,
  renderWithMemoryRouter,
  renderWithStaticRouter,
  renderWithoutRouter,
  createNavigationRouter,
  navigateTo,
  navigateDelta,
};
test/contract.js
const assert = require('node:assert/strict');
const {
  useNavigate,
  NavigationProbe,
  NavigatingComponent,
  renderWithMemoryRouter,
  renderWithStaticRouter,
  renderWithoutRouter,
  createNavigationRouter,
  navigateTo,
  navigateDelta,
} = require('../src/index.js');

// 1. useNavigate throws invariant error when invoked outside of a Router context.
assert.throws(
  () => {
    renderWithoutRouter();
  },
  (err) => {
    return (
      err instanceof Error &&
      /useNavigate\(\) may be used only in the context of a <Router> component/.test(err.message)
    );
  },
  'useNavigate rendered outside Router must throw an invariant error'
);

// 2. useNavigate returns a callable navigation function when rendered within a Router provider.
{
  let inspectedMemory = null;
  const memoryMarkup = renderWithMemoryRouter(
    ['/dashboard?tab=overview#stats'],
    0,
    (ctx) => {
      inspectedMemory = ctx;
    }
  );

  assert.ok(memoryMarkup.includes('Current: /dashboard'), 'MemoryRouter must render probe markup');
  assert.ok(inspectedMemory !== null, 'Probe must capture context inside MemoryRouter');
  assert.strictEqual(typeof inspectedMemory.navigate, 'function', 'useNavigate must return a function');
  assert.strictEqual(inspectedMemory.location.pathname, '/dashboard');
  assert.strictEqual(inspectedMemory.location.search, '?tab=overview');
  assert.strictEqual(inspectedMemory.location.hash, '#stats');

  let inspectedStatic = null;
  const staticMarkup = renderWithStaticRouter('/profile/settings', (ctx) => {
    inspectedStatic = ctx;
  });

  assert.ok(staticMarkup.includes('Current: /profile/settings'), 'StaticRouter must render probe markup');
  assert.ok(inspectedStatic !== null, 'Probe must capture context inside StaticRouter');
  assert.strictEqual(typeof inspectedStatic.navigate, 'function', 'useNavigate must return a function in StaticRouter');
  assert.strictEqual(inspectedStatic.location.pathname, '/profile/settings');
}

// Router configuration for behavioral tests
const routeDefinitions = [
  {
    path: '/',
    id: 'root',
    children: [
      {
        index: true,
        id: 'home',
      },
      {
        path: 'users/:userId',
        id: 'user-detail',
      },
      {
        path: 'settings',
        id: 'settings',
      },
      {
        path: 'analytics',
        id: 'analytics',
      },
    ],
  },
];

// 3. navigate performs push navigation updating the current pathname location and route matches.
{
  const router = createNavigationRouter(routeDefinitions, {
    initialEntries: ['/'],
    initialIndex: 0,
  });

  assert.strictEqual(router.state.location.pathname, '/');
  assert.strictEqual(router.state.matches[0].route.id, 'root');

  navigateTo(router, '/users/alice');
  assert.strictEqual(router.state.location.pathname, '/users/alice');
  assert.strictEqual(router.state.matches.length, 2);
  assert.strictEqual(router.state.matches[1].route.id, 'user-detail');
  assert.strictEqual(router.state.matches[1].params.userId, 'alice');
}

// 4. navigate supports replace option to replace current history entry instead of pushing a new entry.
{
  const router = createNavigationRouter(routeDefinitions, {
    initialEntries: ['/', '/settings'],
    initialIndex: 1,
  });

  assert.strictEqual(router.state.location.pathname, '/settings');
  const previousHistoryIndex = router.state.historyIndex;

  // Replace /settings with /analytics
  navigateTo(router, '/analytics', { replace: true });
  assert.strictEqual(router.state.location.pathname, '/analytics');
  assert.strictEqual(router.state.historyIndex, previousHistoryIndex, 'Replace navigation must maintain current history index');
}

// 5. navigate passes state object accessible via location.state in target route.
{
  const router = createNavigationRouter(routeDefinitions, {
    initialEntries: ['/'],
    initialIndex: 0,
  });

  const navigationPayload = { fromCheckout: true, orderId: 98765 };
  navigateTo(router, { pathname: '/users/bob', search: '?view=orders' }, { state: navigationPayload });

  assert.strictEqual(router.state.location.pathname, '/users/bob');
  assert.strictEqual(router.state.location.search, '?view=orders');
  assert.deepStrictEqual(router.state.location.state, navigationPayload, 'location.state must match navigated payload');
}

// 6. navigate performs delta navigation with negative and positive numbers to traverse history entries.
{
  const router = createNavigationRouter(routeDefinitions, {
    initialEntries: ['/', '/settings', '/analytics'],
    initialIndex: 2,
  });

  assert.strictEqual(router.state.location.pathname, '/analytics');

  // Navigate back 1 step
  navigateDelta(router, -1);
  assert.strictEqual(router.state.location.pathname, '/settings');

  // Navigate back 1 more step
  navigateDelta(router, -1);
  assert.strictEqual(router.state.location.pathname, '/');

  // Navigate forward 2 steps
  navigateDelta(router, 2);
  assert.strictEqual(router.state.location.pathname, '/analytics');
}

console.log('All react-router-dom.useNavigate contract tests passed successfully.');

Исходный сидер

аноним