> ## Documentation Index
> Fetch the complete documentation index at: https://developer.suki.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Build Dictation into a Chart Field

> Use-case tutorial: Run a React sample that mounts Dictation SDK in-field mode on a chart textarea and writes submitted text back with onSubmit

**What you will build**

15 min |
Intermediate

* A React chart screen with one clinical notes field and an **Open dictation** button.
* One shared `SukiAuthManager` and `DictationClient` for the screen.
* In-field Dictation that replaces the field value on submit and leaves it unchanged on cancel.

> [!TIP]
>
> **Using an AI coding tool?**
>
> Copy the prompt below to point your agent at the Dictation SDK skill and [Documentation MCP](https://developer.suki.ai/documentation/references/mcp.md). For every task skill, refer to [AI coding tools](https://developer.suki.ai/documentation/references/ai-coding-tools.md).
>
> Fetch the Dictation SDK skill and connect the documentation MCP.
>
> Add Suki in-field Dictation to a chart field in my React app.
> Fetch the Dictation SDK skill:
> [https://developer.suki.ai/.well-known/agent-skills/suki-dictation-sdk/SKILL.md](https://developer.suki.ai/.well-known/agent-skills/suki-dictation-sdk/SKILL.md)
> Connect the documentation MCP for page search:
> [https://developer.suki.ai/documentation/references/mcp](https://developer.suki.ai/documentation/references/mcp.md)

**Beta**

The Dictation SDK is in beta. Confirm package versions and iframe requirements with your Suki contact before production use.

## Agenda

In this tutorial, you run a small React app that embeds the **Suki Dictation SDK** in **in-field** mode on a chart notes field, then walk through the code that makes it work.

You will learn how to:

1. Load Partner and provider values from environment variables and stop early when one is missing.
2. Create one `SukiAuthManager` and one reusable `DictationClient` for the screen.
3. Give the Dictation iframe a host element and match `fieldId` to the chart field.
4. Mount `<Dictation>` under `DictationProvider` only while Dictation is open.
5. Write the submitted text into the field with `onSubmit`, and close without changes on `onCancel`.

> [!NOTE]
>
> The sample is **not a public GitHub repo**. Use the file explorer below to browse the code, or click **Run locally** to download a zip. Credentials are not included. Copy the patterns you need into your own app.

By the end, clicking **Open dictation**, dictating, and submitting in the hosted panel replaces the notes field with the final text.

## What you build

You build one chart screen. Your app owns the notes field and the **Open dictation** button. Suki renders the microphone, **Submit**, and **Cancel** controls in a hosted iframe inside the host element you provide, and hands the final text back through `onSubmit`.

![Flowchart: SukiAuthManager, DictationClient, DictationProvider, In-field Dictation iframe, Clinical notes field, Close, field unchanged.](https://mintcdn.com/suki-1e08f176/YIYDyOdjNGc_pP0v/documentation/assets/diagrams/tutorials-dictation-sdk-chart-field-1-light.svg?fit=max\&auto=format\&n=YIYDyOdjNGc_pP0v\&q=85\&s=d88432f6cf477972a713b3bdc083ab54)

```mermaid actions={false} theme={"theme":{"light":"one-light","dark":"material-theme-darker"}}
%%{init: {'theme':'base', 'themeVariables': { 'primaryColor':'#FFE148','primaryTextColor':'#111827','primaryBorderColor':'#D4A017','lineColor':'#6F5410','secondaryColor':'#FFF394','tertiaryColor':'#FFFADE','tertiaryTextColor':'#111827','tertiaryBorderColor':'#D4A017','arrowheadColor':'#6F5410','fontSize':'14px','edgeLabelBackground':'#FFFADE'}}}%%
flowchart LR
  A[SukiAuthManager] --> B[DictationClient]
  B --> C[DictationProvider]
  C --> D[In-field Dictation iframe]
  D -->|onSubmit text| E[Clinical notes field]
  D -->|onCancel| F[Close, field unchanged]
```

### Browse the sample project

Use the sidebar in the explorer to open files from the **suki-dictation-chart-field** sample. Partner credentials are not included. Use `.env.example` as the template. **Run locally** downloads a zip you unzip and run with Node.js on your machine.

All of the Dictation logic is in `src/App.tsx`. The other files are a standard Vite and React setup.

## Architecture

Follow this order in your chart screen:

![Flowchart: Read env config, Create auth manager and client once, Capture rootElement, Open dictation, Mount Dictation in-field, onSubmit or onCancel, Unmount Dictation.](https://mintcdn.com/suki-1e08f176/YIYDyOdjNGc_pP0v/documentation/assets/diagrams/tutorials-dictation-sdk-chart-field-2-light.svg?fit=max\&auto=format\&n=YIYDyOdjNGc_pP0v\&q=85\&s=d069b99e38d30d1474be686f41468325)

```mermaid actions={false} theme={"theme":{"light":"one-light","dark":"material-theme-darker"}}
%%{init: {'theme':'base', 'themeVariables': { 'primaryColor':'#FFE148','primaryTextColor':'#111827','primaryBorderColor':'#D4A017','lineColor':'#6F5410','secondaryColor':'#FFF394','tertiaryColor':'#FFFADE','tertiaryTextColor':'#111827','tertiaryBorderColor':'#D4A017','arrowheadColor':'#6F5410','fontSize':'14px','edgeLabelBackground':'#FFFADE'}}}%%
flowchart LR
  A[Read env config] --> B[Create auth manager and client once]
  B --> C[Capture rootElement]
  C --> D[Open dictation]
  D --> E[Mount Dictation in-field]
  E --> F[onSubmit or onCancel]
  F --> G[Unmount Dictation]
```

## Best practices you follow in this tutorial

| Practice | What you do | Reference |
| :- | :- | :- |
| Reuse one client | Create `SukiAuthManager` and `DictationClient` once in `useMemo`. A new client per render tears the iframe down. | [React integration](https://developer.suki.ai/dictation-sdk/react-integration/react.md) |
| Wrap with the provider | Render every `<Dictation>` inside `DictationProvider` with the shared client. | [React integration](https://developer.suki.ai/dictation-sdk/react-integration/react.md) |
| Host the iframe in its own element | Pass a container `<div>` as `rootElement`, not the textarea. | [In-field mode](https://developer.suki.ai/dictation-sdk/guides/in-field-mode.md) |
| Use a stable `fieldId` | Use the same value as the textarea `id` so callbacks map to the right field. | [Callbacks](https://developer.suki.ai/dictation-sdk/guides/callbacks.md) |
| Always handle `onSubmit` | Write `text` into your field state. Without `onSubmit`, Dictation often closes right after the user acts. | [Callbacks](https://developer.suki.ai/dictation-sdk/guides/callbacks.md) |
| Start on staging | Keep `environment: "staging"` until your partner configuration is production-ready. | [Authentication](https://developer.suki.ai/dictation-sdk/guides/authentication.md) |

## Prerequisites and dependencies

> [tab] Prerequisites
>
> Before you begin, make sure you have:
>
> * [Node.js 20.19+](https://nodejs.org/) and npm installed.
> * Completed [Partner onboarding](https://developer.suki.ai/documentation/get-started/partner-onboarding.md) and received staging Partner values.
> * A host that meets [Dictation SDK prerequisites](https://developer.suki.ai/dictation-sdk/prerequisites.md), including CSP and iframe hosts.
> * Chrome or Edge with microphone permission for a live test.
>
> Set these variables in `.env` when you run locally:
>
> | Variable | Purpose |
> | :- | :- |
> | `VITE_SUKI_PARTNER_ID` | Your staging Partner ID |
> | `VITE_SUKI_PARTNER_TOKEN` | Partner Token for the signed-in user |
> | `VITE_SUKI_PROVIDER_ID` | Provider identifier in your system |
> | `VITE_SUKI_PROVIDER_NAME` | Provider full name |
> | `VITE_SUKI_PROVIDER_ORG_ID` | Provider organization identifier |
>
> > [!WARNING]
> >
> > Vite builds every `VITE_*` value into the browser bundle. Use `.env` only for local staging tests, keep it out of source control, and do not ship a build with a hardcoded Partner Token.

> [tab] Dependencies
>
> The sample uses these packages:
>
> | Package | Why you need it |
> | :- | :- |
> | `@suki-sdk/core` | `SukiAuthManager` for Partner authentication |
> | `@suki-sdk/dictation` | `DictationClient`, the reusable Dictation client |
> | `@suki-sdk/dictation-react` | `DictationProvider` and `<Dictation>` for React |
> | `react`, `react-dom` 18 | UI framework (`@suki-sdk/dictation-react` requires React 18) |
> | `vite`, `@vitejs/plugin-react` | Local dev server and build |
>
> To add Dictation to your own React app, install the three Suki packages:
>
> ```shell theme={"theme":{"light":"one-light","dark":"material-theme-darker"}}
> # npm
> npm install @suki-sdk/core @suki-sdk/dictation @suki-sdk/dictation-react
>
> # pnpm
> pnpm add @suki-sdk/core @suki-sdk/dictation @suki-sdk/dictation-react
> ```

## Tutorial steps

Go through each step in order. Run the sample first, then read how each part of `src/App.tsx` works.

**1. Run the Sample Locally**

1. In the explorer above, click **Run locally** to download `suki-dictation-chart-field.zip`.
2. Unzip the archive, then `cd suki-dictation-chart-field`.
3. Copy `.env.example` to `.env` and set your staging Partner and provider values.
4. Run `npm ci`, then `npm run dev`, and open `http://localhost:5173`.
5. Click **Open dictation**, allow the microphone, and dictate a short fake note.

```shell theme={"theme":{"light":"one-light","dark":"material-theme-darker"}}
cd suki-dictation-chart-field
cp .env.example .env
npm ci
npm run dev
```

**Check:** The **Clinical notes** page loads, and **Open dictation** opens the hosted Dictation panel.

**If it fails:** A red message under the field names the missing variable. Add it to `.env` and restart `npm run dev`, because Vite reads `.env` at startup. If the browser console shows `401` on `POST /api/v1/auth/login`, the Partner Token is expired or invalid, so get a fresh one and restart.

**2. Load Configuration from the Environment**

`getRequiredEnv` reads each `VITE_SUKI_*` value and throws when one is missing. The `useMemo` call catches that error and stores it, so the page shows a message and disables **Open dictation** instead of crashing.

```tsx theme={"theme":{"light":"one-light","dark":"material-theme-darker"}}
function getRequiredEnv(name: string) {
const value = import.meta.env[name] as string | undefined;
if (!value) throw new Error(`Missing ${name}. Add it to .env before opening Dictation.`);
return value;
}

const configuration = useMemo(() => {
try {
return {
  partnerId: getRequiredEnv("VITE_SUKI_PARTNER_ID"),
  partnerToken: getRequiredEnv("VITE_SUKI_PARTNER_TOKEN"),
  providerId: getRequiredEnv("VITE_SUKI_PROVIDER_ID"),
  providerName: getRequiredEnv("VITE_SUKI_PROVIDER_NAME"),
  providerOrgId: getRequiredEnv("VITE_SUKI_PROVIDER_ORG_ID"),
};
} catch (caught) {
return caught instanceof Error ? caught : new Error("Unable to configure Dictation.");
}
}, []);
```

**Check:** With a complete `.env`, no red message shows and **Open dictation** is enabled.

**3. Create One Auth Manager and DictationClient**

Build `SukiAuthManager` and `DictationClient` once, inside `useMemo`, so the same client lives for the whole screen. `loginOnInitialize: true` signs in as soon as the auth manager is created. Refer to [Authentication](https://developer.suki.ai/dictation-sdk/guides/authentication.md) for every option.

```tsx theme={"theme":{"light":"one-light","dark":"material-theme-darker"}}
const client = useMemo(() => {
if (configuration instanceof Error) return null;
const authManager = new SukiAuthManager({
partnerId: configuration.partnerId,
partnerToken: configuration.partnerToken,
environment: "staging",
loginOnInitialize: true,
providerId: configuration.providerId,
providerName: configuration.providerName,
providerOrgId: configuration.providerOrgId,
});
return new DictationClient({ authManager });
}, [configuration]);
```

**Check:** Typing in the notes field does not recreate the client or reload the Dictation panel.

**If it fails:** Do not call `new DictationClient` in the component body or once per field. Keep it in `useMemo` with stable dependencies.

**4. Prepare the Chart Field and Root Element**

The textarea `id` and the `fieldId` you pass to Dictation use the same constant, `clinical-notes`. Every callback returns that `fieldId`, so you always know which field the text belongs to.

The empty `<div id="dictation-root">` is where Suki inserts the iframe. A ref captures it after the first render, and the element is stored in state so `<Dictation>` mounts only once the host exists.

```tsx theme={"theme":{"light":"one-light","dark":"material-theme-darker"}}
const fieldId = "clinical-notes";

const rootRef = useRef<HTMLDivElement>(null);
const [rootElement, setRootElement] = useState<HTMLDivElement | null>(null);

useEffect(() => {
setRootElement(rootRef.current);
}, []);

// In the JSX:
<textarea id={fieldId} value={notes} onChange={(event) => setNotes(event.target.value)} rows={12} />
<div ref={rootRef} id="dictation-root" />
```

**Check:** `fieldId` matches the textarea `id`, and `rootElement` points at the `<div>`, not the textarea.

**If it fails:** The iframe sizes itself to its host. If the panel area is blank, give the host a visible width and height and check your CSP. Refer to [In-field mode](https://developer.suki.ai/dictation-sdk/guides/in-field-mode.md).

**5. Mount In-Field Dictation and Handle the Result**

Wrap the Dictation area with `DictationProvider` and the shared client. Mount `<Dictation>` only while `dictationOpen` is true and the host element exists. Unmounting `<Dictation>` closes the hosted session.

`initialText` seeds the session with what is already in the field. `onSubmit` receives `{ fieldId, text }` with the final text, so the sample writes `text` into the notes state and closes the panel. `onCancel` only closes the panel, so cancelling never changes the field.

```tsx theme={"theme":{"light":"one-light","dark":"material-theme-darker"}}
{client ? (
<DictationProvider client={client}>
{dictationOpen && rootElement ? (
  <Dictation
    mode="in-field"
    fieldId={fieldId}
    rootElement={rootElement}
    initialText={notes}
    onSubmit={({ text }) => {
      setNotes(text);
      setDictationOpen(false);
    }}
    onCancel={() => setDictationOpen(false)}
  />
) : null}
</DictationProvider>
) : null}
```

**Check:** Submitting in the panel replaces the notes field with the final text and hides the panel. Cancelling hides the panel and leaves the field as it was.

**If it fails:** Confirm `onSubmit` is passed. Without it, Dictation often closes right after the user acts. Refer to [Callbacks](https://developer.suki.ai/dictation-sdk/guides/callbacks.md).

## Full code example

This is the complete `src/App.tsx` from the sample. Open it in the explorer above to copy it, or download the full project with **Run locally**.

```tsx src/App.tsx theme={"theme":{"light":"one-light","dark":"material-theme-darker"}}
import { useEffect, useMemo, useRef, useState } from "react";
import { SukiAuthManager } from "@suki-sdk/core";
import { DictationClient } from "@suki-sdk/dictation";
import { Dictation, DictationProvider } from "@suki-sdk/dictation-react";

const fieldId = "clinical-notes";

function getRequiredEnv(name: string) {
  const value = import.meta.env[name] as string | undefined;
  if (!value) throw new Error(`Missing ${name}. Add it to .env before opening Dictation.`);
  return value;
}

export function App() {
  const [notes, setNotes] = useState("");
  const [dictationOpen, setDictationOpen] = useState(false);
  const rootRef = useRef<HTMLDivElement>(null);
  const [rootElement, setRootElement] = useState<HTMLDivElement | null>(null);

  const configuration = useMemo(() => {
    try {
      return {
        partnerId: getRequiredEnv("VITE_SUKI_PARTNER_ID"),
        partnerToken: getRequiredEnv("VITE_SUKI_PARTNER_TOKEN"),
        providerId: getRequiredEnv("VITE_SUKI_PROVIDER_ID"),
        providerName: getRequiredEnv("VITE_SUKI_PROVIDER_NAME"),
        providerOrgId: getRequiredEnv("VITE_SUKI_PROVIDER_ORG_ID"),
      };
    } catch (caught) {
      return caught instanceof Error ? caught : new Error("Unable to configure Dictation.");
    }
  }, []);

  const client = useMemo(() => {
    if (configuration instanceof Error) return null;
    const authManager = new SukiAuthManager({
        partnerId: configuration.partnerId,
        partnerToken: configuration.partnerToken,
        environment: "staging",
        loginOnInitialize: true,
        providerId: configuration.providerId,
        providerName: configuration.providerName,
        providerOrgId: configuration.providerOrgId,
    });
    return new DictationClient({ authManager });
  }, [configuration]);

  useEffect(() => {
    setRootElement(rootRef.current);
  }, []);

  return (
    <main>
      <h1>Clinical notes</h1>
      <p>Dictate into the hosted Suki panel, then submit to update this chart field.</p>
      <label htmlFor={fieldId}>Notes</label>
      <textarea
        id={fieldId}
        value={notes}
        onChange={(event) => setNotes(event.target.value)}
        placeholder="Clinical notes appear here after Dictation is submitted."
        rows={12}
      />
      {configuration instanceof Error ? <p role="alert">{configuration.message}</p> : null}
      {!dictationOpen ? (
        <button type="button" onClick={() => setDictationOpen(true)} disabled={!client}>
          Open dictation
        </button>
      ) : null}
      <div ref={rootRef} id="dictation-root" />
      {client ? (
        <DictationProvider client={client}>
          {dictationOpen && rootElement ? (
            <Dictation
              mode="in-field"
              fieldId={fieldId}
              rootElement={rootElement}
              initialText={notes}
              onSubmit={({ text }) => {
                setNotes(text);
                setDictationOpen(false);
              }}
              onCancel={() => setDictationOpen(false)}
            />
          ) : null}
        </DictationProvider>
      ) : null}
    </main>
  );
}
```

## How this tutorial was tested

This tutorial is tested on the following:

* Node.js 20.20 on macOS
* `@suki-sdk/core` 0.1.3, `@suki-sdk/dictation` 0.1.0-beta.3, `@suki-sdk/dictation-react` 0.1.0-beta-3, and React 18.3
* Clean `npm ci` and `npm run build` (TypeScript strict mode) from the downloaded zip
* Local dev server with `npm run dev`, with Partner and provider values in a local `.env`

## Common mistakes

| Mistake | What to do instead |
| :- | :- |
| Creating `DictationClient` in the component body or per field | Create it once in `useMemo` and reuse it for the screen |
| Rendering `<Dictation>` outside `DictationProvider` | Wrap it with `<DictationProvider client={client}>` |
| Passing the textarea as `rootElement` | Pass a separate host `<div>` with a visible width and height |
| `fieldId` that does not match the field you update | Use one constant for the textarea `id` and `fieldId` |
| Leaving out `onSubmit` | Always pass `onSubmit` and write `text` into your field state |
| Writing text in `onCancel` | Only close the panel in `onCancel`; persist text only from `onSubmit` |
| Reusing an expired Partner Token | A `401` on login means the token is expired or invalid; get a fresh one and restart the dev server |
| Committing `.env` | Keep `.env` in `.gitignore`; share `.env.example` instead |

## Next steps

&#x20;**[In-field mode](https://developer.suki.ai/dictation-sdk/guides/in-field-mode.md)** - Host element sizing, `fieldId`, and launch controls.

&#x20;**[Callbacks](https://developer.suki.ai/dictation-sdk/guides/callbacks.md)** - `onSubmit`, `onCancel`, and `onDraft` payloads and timing.

&#x20;**[Write Dictation to an EHR field](https://developer.suki.ai/documentation/cookbooks/dictation-onsubmit-chart-field.md)** - JavaScript and React recipe for the same `onSubmit` pattern.

&#x20;**[Dictation SDK prerequisites](https://developer.suki.ai/dictation-sdk/prerequisites.md)** - CSP and iframe hosts to allow.

&#x20;**[Build a Dictation streaming client](https://developer.suki.ai/documentation/tutorials/dictation-websocket-code-example.md)** - Stream audio to the Dictation API without the hosted UI.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.