How to track form-field drop-off without values in React

Track field focus, validation, and completion with fixed metadata instead of entered values. Build a React fixture with completed and partial attempts, then verify the real event payloads in about 20 minutes.

  • React
  • Vite
  • Unified SDK 1.2.1
  • 20 min

Chris Tam · Last updated 13 November 2026

Product analytics can show which form steps people reach without collecting their answers. I'll instrument a local profile form with name, email, and team-size fields. It validates locally; it doesn't create an account or send email.

In this tutorial, I'll record field progress with fixed metadata, distinguish attempts, and compare a completed path with an explicit exit. The React analytics tutorial covers general setup; this example includes its own files.

What you'll build

A form that sends Form Started, field focus and validation events, and either Form Submitted or an explicit Form Exited. Each event has a random attempt_id. Field events carry an approved field_id and validation reason/phase; entered values are not passed to analytics.

Prerequisites

  • Node.js 22.12 or later and Corepack for pnpm.
  • An Amplitude test project and its ingestion API key. Open Organization settings > API Keys and select the test project.
  • The project data center, US or EU. Preserve your existing consent flow when adapting the example.

No Amplitude account yet? A free account is enough for this tutorial; nothing here needs a paid plan. Sign up for free to get your project API key.

1. Create the standalone app

I'll use the Browser Unified SDK package installation in a small Vite app. The versions below are pinned to the tested example.

Terminal
mkdir react-form-dropoff
cd react-form-dropoff
mkdir -p src tests
corepack enable
package.json
{
  "name": "amplitude-react-form-dropoff",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "packageManager": "pnpm@10.33.2+sha512.a90faf6feeab71ad6c6e57f94e0fe1a12f5dcc22cd754db40ae9593eb6a3e0b6b12e3540218bb37ae083404b1f2ce6db2a4121e979829b4aff94b99f49da1cf8",
  "engines": {
    "node": ">=22.12.0",
    "pnpm": ">=10.21.0"
  },
  "scripts": {
    "dev": "vite --host 127.0.0.1",
    "build": "vite build",
    "preview": "vite preview --host 127.0.0.1",
    "test": "node --test tests/*.test.mjs"
  },
  "dependencies": {
    "@amplitude/unified": "1.2.1",
    "react": "19.3.1",
    "react-dom": "19.3.1"
  },
  "devDependencies": {
    "vite": "8.3.6"
  }
}
pnpm-workspace.yaml
minimumReleaseAge: 10080
trustPolicy: no-downgrade
.gitignore
node_modules/
dist/
.env
.env.local
.env.*.local
index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Form drop-off demo</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>
.env.example
VITE_AMPLITUDE_API_KEY=
VITE_AMPLITUDE_SERVER_ZONE=US
Terminal
corepack prepare pnpm@10.33.2 --activate
pnpm install
cp .env.example .env.local

Put the test-project key in VITE_AMPLITUDE_API_KEY in .env.local, and set VITE_AMPLITUDE_SERVER_ZONE to US or EU. Vite exposes VITE_ variables in the browser bundle. The project API key is public and has the minimum scope needed to ingest data; a server secret key stays out of browser code.

In an existing application, merge the changes into its current Amplitude module and application flow. Keep authentication, consent, routes, and other instrumentation. Don't add another SDK installation or replace production files with the demo.

2. Define field metadata separately from values

I'll map local validation results into a small event schema. The custom-event guide covers explicit event names and properties; the field IDs and validation reasons here belong to this application.

src/form-events.js
export const fields = ['display_name', 'email', 'team_size'];
const types = ['Form Started', 'Form Field Focused', 'Form Field Completed', 'Form Field Invalid', 'Form Submitted', 'Form Exited'];
const reasons = ['valid', 'required', 'name_length', 'email_format', 'team_choice'];

export function validation(field, value) {
  if (!fields.includes(field)) throw new Error('Unknown field.');
  if (typeof value !== 'string' || !value.trim()) return 'required';
  if (field === 'display_name' && (value.trim().length < 2 || value.length > 60)) return 'name_length';
  if (field === 'email' && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) return 'email_format';
  if (field === 'team_size' && !['1-10', '11-50', '51+'].includes(value)) return 'team_choice';
  return 'valid';
}

export function projectFormEvent(type, attemptId, metadata = {}) {
  if (!types.includes(type) || !/^[0-9a-f-]{36}$/i.test(attemptId)) return null;
  if (type.startsWith('Form Field') && !fields.includes(metadata.field)) return null;
  if (metadata.reason !== undefined && !reasons.includes(metadata.reason)) return null;
  if (metadata.phase !== undefined && !['blur', 'submit'].includes(metadata.phase)) return null;
  return {
    type,
    properties: { form_id: 'workspace_profile', attempt_id: attemptId,
      ...(fields.includes(metadata.field) ? { field_id: metadata.field } : {}),
      ...(reasons.includes(metadata.reason) ? { validation_reason: metadata.reason } : {}),
      ...(['blur', 'submit'].includes(metadata.phase) ? { validation_phase: metadata.phase } : {}),
    },
  };
}

validation returns a fixed reason, never the entered value or a value-containing error message. projectFormEvent constructs approved properties rather than copying an input object. Only known event names, field IDs, reasons, phases, and a generated attempt ID are accepted.

Why. A free-text value can leak through an error message or nested object even when you omit the primary input key. Keep the analytics descriptor separate from the form state and inspect the entire event during verification.

3. Send only the projected event

I'll pass the projected name and properties to the same SDK instance used by the app. Telemetry failure is logged separately from local validation, so a network failure doesn't make a valid form fail.

src/analytics.js
import * as amplitude from '@amplitude/unified';
import { projectFormEvent } from './form-events.js';

let ready;
let enabled = false;
export function initializeAnalytics() {
  const apiKey = import.meta.env.VITE_AMPLITUDE_API_KEY?.trim();
  if (!apiKey) return Promise.resolve({ status: 'disabled', deviceId: null });
  if (!ready) ready = amplitude.initAll(apiKey, {
    serverZone: import.meta.env.VITE_AMPLITUDE_SERVER_ZONE === 'EU' ? 'EU' : 'US',
    analytics: { autocapture: false, remoteConfig: { fetchRemoteConfig: false } },
    sessionReplay: { sampleRate: 0 }, engagement: { skip: true },
  }).then(() => {
    enabled = true;
    return { status: 'ready', deviceId: amplitude.getDeviceId() };
  }).catch((error) => {
    console.error('Analytics initialization failed', error);
    return { status: 'error', deviceId: null };
  });
  return ready;
}

export function recordFormEvent(type, attemptId, metadata) {
  const event = projectFormEvent(type, attemptId, metadata);
  if (!enabled || !event) return;
  void amplitude.track(event.type, event.properties).promise.then((result) => {
    if (result.code !== 200) console.warn('Form telemetry not accepted:', result.message);
  }).catch((error) => console.warn('Form telemetry failed', error));
}

Autocapture is off, including automatic form and element collection. Replay sampling is zero and guides and surveys are skipped. Analytics remote fetching is disabled so these local choices apply. This keeps the example focused on deliberate metadata events; another instance or product needs its own collection review.

MCP. Have your coding agent read the current tracking options through the Docs MCP server before merging the example into an existing setup. It reads public docs and doesn't inspect your users' form answers.

4. Attach metadata events to the form lifecycle

I'll start an attempt on the first interaction, record focus and blur validation, and submit only after local validation passes. A ref keeps Form Started to one call per attempt. Starting again creates a new attempt ID and clears the component state.

src/App.jsx
import React, { useRef, useState } from 'react';
import { fields, validation } from './form-events.js';
import { recordFormEvent } from './analytics.js';

const empty = () => ({ display_name: '', email: '', team_size: '' });
export function App({ analytics }) {
  const [values, setValues] = useState(empty);
  const [attempt, setAttempt] = useState(() => crypto.randomUUID());
  const [stage, setStage] = useState('editing');
  const [message, setMessage] = useState('Use synthetic values only.');
  const started = useRef(false);
  function ensureStarted() {
    if (!started.current) { started.current = true; recordFormEvent('Form Started', attempt); }
  }
  function focus(field) { ensureStarted(); recordFormEvent('Form Field Focused', attempt, { field }); }
  function blur(field) {
    const reason = validation(field, values[field]);
    recordFormEvent(reason === 'valid' ? 'Form Field Completed' : 'Form Field Invalid', attempt, { field, reason, phase: 'blur' });
  }
  function submit(event) {
    event.preventDefault(); ensureStarted();
    const invalid = fields.filter((field) => validation(field, values[field]) !== 'valid');
    if (invalid.length) {
      for (const field of invalid) recordFormEvent('Form Field Invalid', attempt, { field, reason: validation(field, values[field]), phase: 'submit' });
      setMessage('Fix the required fields and use the listed team size.'); return;
    }
    recordFormEvent('Form Submitted', attempt); setStage('completed');
    setMessage('Local validation completed. No account was created.');
  }
  function leave() {
    ensureStarted(); recordFormEvent('Form Exited', attempt); setStage('exited');
    setMessage('Left this demo attempt without submitting.');
  }
  function restart() {
    setAttempt(crypto.randomUUID()); setValues(empty()); setStage('editing'); started.current = false;
    setMessage('New attempt. Use synthetic values only.');
  }
  return (
    <main>
      <p className="eyebrow">FORM TELEMETRY DEMO</p><h1>Track progress without values</h1>
      <p>This form validates locally. It doesn't create an account or send email. Analytics receives fixed field IDs and validation reasons; the entered values stay in this component's state.</p>
      {stage === 'editing' ? <form noValidate onSubmit={submit}>
        <label htmlFor="display_name">Demo display name</label>
        <input id="display_name" value={values.display_name} onFocus={() => focus('display_name')} onBlur={() => blur('display_name')}
          onChange={(e) => setValues({ ...values, display_name: e.target.value })} />
        <label htmlFor="email">Demo email</label>
        <input id="email" type="email" value={values.email} onFocus={() => focus('email')} onBlur={() => blur('email')}
          onChange={(e) => setValues({ ...values, email: e.target.value })} />
        <label htmlFor="team_size">Team size</label>
        <select id="team_size" value={values.team_size} onFocus={() => focus('team_size')} onBlur={() => blur('team_size')}
          onChange={(e) => setValues({ ...values, team_size: e.target.value })}>
          <option value="">Choose a size</option><option value="1-10">1-10</option><option value="11-50">11-50</option><option value="51+">51+</option>
        </select>
        <button id="submit" type="submit">Submit locally</button>
        <button id="leave" type="button" onClick={leave}>Leave form (demo)</button>
      </form> : <button id="restart" onClick={restart}>Start another attempt</button>}
      <p role="status">{message}</p>
      <p>Stage: <strong id="stage">{stage}</strong></p>
      <p>Attempt: <code id="attempt-id">{attempt}</code></p>
      <aside><p>Analytics: <strong id="analytics-status">{analytics.status}</strong></p>
        <p>Device ID: <code id="device-id">{analytics.deviceId ?? 'not initialized'}</code></p></aside>
    </main>
  );
}
src/style.css
:root { font-family: Helvetica, Arial, sans-serif; color: #000000; background: #F2F4F8; }
body { margin: 0; }
main { max-width: 760px; margin: 40px auto; padding: 32px; background: #FFFFFF; border-radius: 16px; }
h1 { font-size: 36px; }
p { line-height: 1.5; }
.eyebrow { font-size: 12px; letter-spacing: 0.08em; }
nav { display: flex; gap: 20px; flex-wrap: wrap; padding: 16px 0; }
a { color: #0052F2; }
section, aside { border-top: 1px solid #D5D9E0; margin-top: 24px; padding-top: 24px; }
label { display: block; margin-bottom: 8px; }
button, select, [role='button'] { font: inherit; padding: 10px 14px; margin: 0 12px 12px 0; border: 1px solid #000000; border-radius: 6px; color: #000000; background: #FFFFFF; }
button, [role='button'] { cursor: pointer; }
#save-settings { color: #FFFFFF; background: #0052F2; border-color: #0052F2; }
[role='button'] { display: inline-block; }
:focus-visible { outline: 3px solid #0052F2; outline-offset: 3px; }
code { overflow-wrap: anywhere; }
@media (max-width: 800px) { main { margin: 16px; padding: 24px; } }

button:disabled, select:disabled { opacity: 0.6; cursor: wait; }
form { margin-top: 24px; }

The Leave form control simulates an explicit exit. It doesn't detect every tab closure. A partial attempt has field activity and an exit event but no Form Submitted. A completed attempt represents local validation, not a server-confirmed signup.

Focus and blur can repeat when a person revisits a field. Invalid blur and invalid submission have different validation_phase values. Use attempt_id to count attempts and compare their stages, rather than treating raw focus totals as unique completions.

5. Mount and test the app

I'll start the app once outside the React component tree and retain Strict Mode. The tests check fixed validation reasons and reject values outside the event schema.

src/main.jsx
import React, { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { App } from './App.jsx';
import { initializeAnalytics } from './analytics.js';
import './style.css';

initializeAnalytics().then((analytics) => {
  createRoot(document.getElementById('root')).render(<StrictMode><App analytics={analytics} /></StrictMode>);
});
tests/form.test.mjs
import test from 'node:test';
import assert from 'node:assert/strict';
import { projectFormEvent, validation } from '../src/form-events.js';
const attempt = '11111111-2222-4333-8444-555555555555';
const marker = 'PRIVATE_FORM_FIXTURE_20261113';

test('validation produces only fixed reasons for missing, malformed and complete fields', () => {
  assert.equal(validation('email', marker), 'email_format');
  assert.equal(validation('email', `${marker}@example.test`), 'valid');
  assert.equal(validation('display_name', ''), 'required');
  assert.equal(validation('display_name', marker), 'valid');
  assert.equal(validation('team_size', marker), 'team_choice');
  assert.equal(validation('team_size', '1-10'), 'valid');
});
test('projection does not copy raw or nested values into any event', () => {
  const result = projectFormEvent('Form Field Invalid', attempt, { field: 'email', reason: 'email_format', phase: 'blur', value: marker, nested: { text: marker } });
  assert.equal(result.properties.field_id, 'email');
  assert.equal(result.properties.validation_reason, 'email_format');
  assert.ok(!JSON.stringify(result).includes(marker));
  assert.equal(projectFormEvent('Form Submitted', marker), null);
  assert.equal(projectFormEvent('Form Field Focused', attempt, { field: marker }), null);
});
Terminal
pnpm test
pnpm build
pnpm dev

Open the local URL printed by Vite.

Verify it worked

Use synthetic marker values for the privacy check, and compare the completed and partial attempt IDs separately.

  1. Blank key: Run with no key, enter synthetic values and submit a valid form. Confirm local completion still works while analytics is disabled. Then add the test-project key and rebuild.
  2. Completed attempt: Enter PRIVATE_FORM_FIXTURE_20261113 as the name and initially as an invalid email. Submit to exercise fixed validation reasons. Correct the email to PRIVATE_FORM_FIXTURE_20261113@example.test, focus and choose the team-size dropdown, then submit. Note the attempt ID and confirm local completion.
  3. Partial attempt: Start another attempt, enter the synthetic name, and choose Leave form. Confirm its new attempt ID differs and it has no submission. This is an explicit simulated exit, not a claim that browser unload events are always observable.
  4. Complete SDK bodies: Confirm uploads return HTTP 200, then use Instrumentation Explorer for individual bodies because SDK requests can be compressed. Scan the whole event for the marker, email, and raw input values. The event properties should contain only form_id, attempt_id, and the applicable field/reason/phase metadata.
  5. Processed history: Search the displayed device ID in User Lookup and inspect Activity, allowing ten seconds to one minute for events. Match Form Submitted to the completed attempt and Form Exited to the partial attempt. Inspect a field event for its fixed field ID and reason. A missing submission within your observation window is evidence of that tested partial path; choose an analysis window before interpreting production drop-off.

Troubleshooting

A field produces multiple focus events

A person can return to a field. Count distinct attempts for an attempt-level funnel and use the event type, field ID, and validation phase to interpret repeated interactions.

Invalid fields appear twice after clicking submit

The focused field may blur before the submit handler validates the form. validation_phase distinguishes the blur observation from the submit observation. Don't sum them as two unique attempts.

A marker appears in the payload

Check every top-level and nested field, not just the main event properties. Remove spreads of form state, dynamic event names, value-containing error messages, and automatic capture paths that weren't reviewed. Verify other SDK instances separately.

The dropdown has no focus event in an automated test

Programmatic option selection may change the value without focusing the control. Focus the select and move away to exercise its actual focus/blur path. Local submission still validates all fields.

A partial attempt has no exit event

The explicit Leave control emits Form Exited. A tab closure or navigation may not run that handler. Base drop-off analysis on the sequence and an appropriate completion window rather than requiring a reliable exit event.

Full code reference

The complete runnable example includes the lockfile. These are the complete application and test files, combined for copying. Keep environment values local.

Full code reference
===== package.json =====
{
  "name": "amplitude-react-form-dropoff",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "packageManager": "pnpm@10.33.2+sha512.a90faf6feeab71ad6c6e57f94e0fe1a12f5dcc22cd754db40ae9593eb6a3e0b6b12e3540218bb37ae083404b1f2ce6db2a4121e979829b4aff94b99f49da1cf8",
  "engines": {
    "node": ">=22.12.0",
    "pnpm": ">=10.21.0"
  },
  "scripts": {
    "dev": "vite --host 127.0.0.1",
    "build": "vite build",
    "preview": "vite preview --host 127.0.0.1",
    "test": "node --test tests/*.test.mjs"
  },
  "dependencies": {
    "@amplitude/unified": "1.2.1",
    "react": "19.3.1",
    "react-dom": "19.3.1"
  },
  "devDependencies": {
    "vite": "8.3.6"
  }
}

===== pnpm-workspace.yaml =====
minimumReleaseAge: 10080
trustPolicy: no-downgrade

===== .gitignore =====
node_modules/
dist/
.env
.env.local
.env.*.local

===== index.html =====
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Form drop-off demo</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>

===== .env.example =====
VITE_AMPLITUDE_API_KEY=
VITE_AMPLITUDE_SERVER_ZONE=US

===== src/form-events.js =====
export const fields = ['display_name', 'email', 'team_size'];
const types = ['Form Started', 'Form Field Focused', 'Form Field Completed', 'Form Field Invalid', 'Form Submitted', 'Form Exited'];
const reasons = ['valid', 'required', 'name_length', 'email_format', 'team_choice'];

export function validation(field, value) {
  if (!fields.includes(field)) throw new Error('Unknown field.');
  if (typeof value !== 'string' || !value.trim()) return 'required';
  if (field === 'display_name' && (value.trim().length < 2 || value.length > 60)) return 'name_length';
  if (field === 'email' && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) return 'email_format';
  if (field === 'team_size' && !['1-10', '11-50', '51+'].includes(value)) return 'team_choice';
  return 'valid';
}

export function projectFormEvent(type, attemptId, metadata = {}) {
  if (!types.includes(type) || !/^[0-9a-f-]{36}$/i.test(attemptId)) return null;
  if (type.startsWith('Form Field') && !fields.includes(metadata.field)) return null;
  if (metadata.reason !== undefined && !reasons.includes(metadata.reason)) return null;
  if (metadata.phase !== undefined && !['blur', 'submit'].includes(metadata.phase)) return null;
  return {
    type,
    properties: { form_id: 'workspace_profile', attempt_id: attemptId,
      ...(fields.includes(metadata.field) ? { field_id: metadata.field } : {}),
      ...(reasons.includes(metadata.reason) ? { validation_reason: metadata.reason } : {}),
      ...(['blur', 'submit'].includes(metadata.phase) ? { validation_phase: metadata.phase } : {}),
    },
  };
}

===== src/analytics.js =====
import * as amplitude from '@amplitude/unified';
import { projectFormEvent } from './form-events.js';

let ready;
let enabled = false;
export function initializeAnalytics() {
  const apiKey = import.meta.env.VITE_AMPLITUDE_API_KEY?.trim();
  if (!apiKey) return Promise.resolve({ status: 'disabled', deviceId: null });
  if (!ready) ready = amplitude.initAll(apiKey, {
    serverZone: import.meta.env.VITE_AMPLITUDE_SERVER_ZONE === 'EU' ? 'EU' : 'US',
    analytics: { autocapture: false, remoteConfig: { fetchRemoteConfig: false } },
    sessionReplay: { sampleRate: 0 }, engagement: { skip: true },
  }).then(() => {
    enabled = true;
    return { status: 'ready', deviceId: amplitude.getDeviceId() };
  }).catch((error) => {
    console.error('Analytics initialization failed', error);
    return { status: 'error', deviceId: null };
  });
  return ready;
}

export function recordFormEvent(type, attemptId, metadata) {
  const event = projectFormEvent(type, attemptId, metadata);
  if (!enabled || !event) return;
  void amplitude.track(event.type, event.properties).promise.then((result) => {
    if (result.code !== 200) console.warn('Form telemetry not accepted:', result.message);
  }).catch((error) => console.warn('Form telemetry failed', error));
}

===== src/App.jsx =====
import React, { useRef, useState } from 'react';
import { fields, validation } from './form-events.js';
import { recordFormEvent } from './analytics.js';

const empty = () => ({ display_name: '', email: '', team_size: '' });
export function App({ analytics }) {
  const [values, setValues] = useState(empty);
  const [attempt, setAttempt] = useState(() => crypto.randomUUID());
  const [stage, setStage] = useState('editing');
  const [message, setMessage] = useState('Use synthetic values only.');
  const started = useRef(false);
  function ensureStarted() {
    if (!started.current) { started.current = true; recordFormEvent('Form Started', attempt); }
  }
  function focus(field) { ensureStarted(); recordFormEvent('Form Field Focused', attempt, { field }); }
  function blur(field) {
    const reason = validation(field, values[field]);
    recordFormEvent(reason === 'valid' ? 'Form Field Completed' : 'Form Field Invalid', attempt, { field, reason, phase: 'blur' });
  }
  function submit(event) {
    event.preventDefault(); ensureStarted();
    const invalid = fields.filter((field) => validation(field, values[field]) !== 'valid');
    if (invalid.length) {
      for (const field of invalid) recordFormEvent('Form Field Invalid', attempt, { field, reason: validation(field, values[field]), phase: 'submit' });
      setMessage('Fix the required fields and use the listed team size.'); return;
    }
    recordFormEvent('Form Submitted', attempt); setStage('completed');
    setMessage('Local validation completed. No account was created.');
  }
  function leave() {
    ensureStarted(); recordFormEvent('Form Exited', attempt); setStage('exited');
    setMessage('Left this demo attempt without submitting.');
  }
  function restart() {
    setAttempt(crypto.randomUUID()); setValues(empty()); setStage('editing'); started.current = false;
    setMessage('New attempt. Use synthetic values only.');
  }
  return (
    <main>
      <p className="eyebrow">FORM TELEMETRY DEMO</p><h1>Track progress without values</h1>
      <p>This form validates locally. It doesn't create an account or send email. Analytics receives fixed field IDs and validation reasons; the entered values stay in this component's state.</p>
      {stage === 'editing' ? <form noValidate onSubmit={submit}>
        <label htmlFor="display_name">Demo display name</label>
        <input id="display_name" value={values.display_name} onFocus={() => focus('display_name')} onBlur={() => blur('display_name')}
          onChange={(e) => setValues({ ...values, display_name: e.target.value })} />
        <label htmlFor="email">Demo email</label>
        <input id="email" type="email" value={values.email} onFocus={() => focus('email')} onBlur={() => blur('email')}
          onChange={(e) => setValues({ ...values, email: e.target.value })} />
        <label htmlFor="team_size">Team size</label>
        <select id="team_size" value={values.team_size} onFocus={() => focus('team_size')} onBlur={() => blur('team_size')}
          onChange={(e) => setValues({ ...values, team_size: e.target.value })}>
          <option value="">Choose a size</option><option value="1-10">1-10</option><option value="11-50">11-50</option><option value="51+">51+</option>
        </select>
        <button id="submit" type="submit">Submit locally</button>
        <button id="leave" type="button" onClick={leave}>Leave form (demo)</button>
      </form> : <button id="restart" onClick={restart}>Start another attempt</button>}
      <p role="status">{message}</p>
      <p>Stage: <strong id="stage">{stage}</strong></p>
      <p>Attempt: <code id="attempt-id">{attempt}</code></p>
      <aside><p>Analytics: <strong id="analytics-status">{analytics.status}</strong></p>
        <p>Device ID: <code id="device-id">{analytics.deviceId ?? 'not initialized'}</code></p></aside>
    </main>
  );
}

===== src/style.css =====
:root { font-family: Helvetica, Arial, sans-serif; color: #000000; background: #F2F4F8; }
body { margin: 0; }
main { max-width: 760px; margin: 40px auto; padding: 32px; background: #FFFFFF; border-radius: 16px; }
h1 { font-size: 36px; }
p { line-height: 1.5; }
.eyebrow { font-size: 12px; letter-spacing: 0.08em; }
nav { display: flex; gap: 20px; flex-wrap: wrap; padding: 16px 0; }
a { color: #0052F2; }
section, aside { border-top: 1px solid #D5D9E0; margin-top: 24px; padding-top: 24px; }
label { display: block; margin-bottom: 8px; }
button, select, [role='button'] { font: inherit; padding: 10px 14px; margin: 0 12px 12px 0; border: 1px solid #000000; border-radius: 6px; color: #000000; background: #FFFFFF; }
button, [role='button'] { cursor: pointer; }
#save-settings { color: #FFFFFF; background: #0052F2; border-color: #0052F2; }
[role='button'] { display: inline-block; }
:focus-visible { outline: 3px solid #0052F2; outline-offset: 3px; }
code { overflow-wrap: anywhere; }
@media (max-width: 800px) { main { margin: 16px; padding: 24px; } }

button:disabled, select:disabled { opacity: 0.6; cursor: wait; }
form { margin-top: 24px; }

===== src/main.jsx =====
import React, { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { App } from './App.jsx';
import { initializeAnalytics } from './analytics.js';
import './style.css';

initializeAnalytics().then((analytics) => {
  createRoot(document.getElementById('root')).render(<StrictMode><App analytics={analytics} /></StrictMode>);
});

===== tests/form.test.mjs =====
import test from 'node:test';
import assert from 'node:assert/strict';
import { projectFormEvent, validation } from '../src/form-events.js';
const attempt = '11111111-2222-4333-8444-555555555555';
const marker = 'PRIVATE_FORM_FIXTURE_20261113';

test('validation produces only fixed reasons for missing, malformed and complete fields', () => {
  assert.equal(validation('email', marker), 'email_format');
  assert.equal(validation('email', `${marker}@example.test`), 'valid');
  assert.equal(validation('display_name', ''), 'required');
  assert.equal(validation('display_name', marker), 'valid');
  assert.equal(validation('team_size', marker), 'team_choice');
  assert.equal(validation('team_size', '1-10'), 'valid');
});
test('projection does not copy raw or nested values into any event', () => {
  const result = projectFormEvent('Form Field Invalid', attempt, { field: 'email', reason: 'email_format', phase: 'blur', value: marker, nested: { text: marker } });
  assert.equal(result.properties.field_id, 'email');
  assert.equal(result.properties.validation_reason, 'email_format');
  assert.ok(!JSON.stringify(result).includes(marker));
  assert.equal(projectFormEvent('Form Submitted', marker), null);
  assert.equal(projectFormEvent('Form Field Focused', attempt, { field: marker }), null);
});

Hand it to your agent

Use this prompt to adapt the example to an existing application.

Implementation prompt
Use https://amplitude.com/build/react-form-dropoff and its linked source.
Inspect the current SDK entry point and application flow first. Merge into existing
files; preserve auth, consent, routes, and other instrumentation. Fetch current
Amplitude docs for the installed SDK. Keep the ingestion key in the existing
environment mechanism and never add server secrets to browser code.

Use fixed event/field names and validation-reason enums. Keep raw form state and
error text out of telemetry descriptors. Construct event properties explicitly;
never spread input values into track calls. Generate one attempt ID per fresh
form attempt and preserve it through that attempt's events. Distinguish blur
from submit validation and repeated focus from unique attempts. Keep automatic
form/element capture and other products within their own reviewed policy.
Test synthetic markers across the entire real payload, completed/partial attempts,
and processed metadata. Don't equate local validation with a confirmed signup
or promise reliable events on every tab closure.

Test blank-key startup and failure paths as well as success. Confirm real SDK
uploads and processed data separately from local tests. Report changed files and
remaining coverage limits.

What this unlocks

Product analytics can compare completed and partial attempt paths by the fixed field metadata.

Session replay can add visual context only after its own masking and capture behavior is configured separately.

Feature flags can vary a later form design while the same attempt-level completion events measure behavior.

Guides and surveys can ask about the form experience when enabled and configured separately.

Frequently asked questions

Are email values sent by this form?

The example passes the fixed field ID email and validation reasons, not the entered email. Its complete SDK event bodies are tested with synthetic markers. This scope doesn't cover another client, logging system, automatic collector, or product.

Does Form Submitted mean an account exists?

Here it means local validation completed. A real signup or save should have a separate confirmed backend outcome where that operation commits. Keep event names aligned with what the code establishes.

Why use an attempt ID as well as a user ID?

One person can start a form more than once. The random attempt ID separates those paths within the event stream, while the SDK's identity still connects activity to the person or device.

Next steps

Amplitude is the leading all-in-one analytics platform for building better products. Product and engineering teams use Amplitude to connect product analytics and web analytics with session replay, heatmaps, experimentation, feature flags, and guides and surveys in one unified workflow, with AI agents working across all of it. Learn how Amplitude is building self-improving products with Wave, helping teams turn product data into PRs.

Connect the next event

Make the identity and properties explicit, then verify them in your test project.