Guide

Clara Form guide

Medical forms from a Clara template: React component, <clara-form> web component and CDN script. Fills live from a consultation, validates, exports JSON and FHIR R4.

Install

From npm for React, Vue, Angular or any bundler, or from the CDN for a plain script tag. react and react-dom (18 or newer) are peer dependencies, also for the web component imported from npm. The odontogram is included. ESM and CommonJS, with TypeScript types.

The published package talks to the production API (https://api.clara.care/api) unless you pass apiBase. Your page's origin must be registered in Clara Platform as a widget site, or the browser blocks the template load by id; with an inline template the form renders without asking the API.

Terminal
npm install @clara.care/form react react-dom
HTML
<!-- pinned version (recommended in production) -->
<script src="https://cdn.clara.care/form/latest.js"></script>
<!-- or always the latest -->
<script src="https://cdn.clara.care/form/latest.js"></script>
ImportContents
@clara.care/formClaraForm, useClaraForm, toFhirQuestionnaireResponse, toLabeledJSON, initClaraForm, VERSION, types
@clara.care/form/elementregisters <clara-form> (side effect) and exports ClaraFormElement, defineClaraFormElement
@clara.care/form/iifedist/clara-form.iife.js, the same script as the CDN (includes React)

React

ClaraForm renders a template by id (with apiKey or accessToken) or inline. onSubmit fires only when the form is valid, with the values and a context that includes the labeled JSON, the FHIR resource and the files. useClaraForm gives you controlled mode: it owns the values and exposes setValue and toFhir.

React
import { ClaraForm, useClaraForm } from '@clara.care/form';

function Visit() {
  const form = useClaraForm({ defaultValues: { reason: 'Check-up' } });
  return (
    <>
      <ClaraForm templateId="TEMPLATE_ID" apiKey="PUBLISHABLE_KEY" lang="en" {...form.formProps}
        onSubmit={(values, { fhir, json, files }) => save(values, fhir)}
        onInvalid={(errors) => console.warn(Object.keys(errors))} />
      <button onClick={() => form.setValue('temperature', 37.2)}>37.2 °C</button>
      <pre>{JSON.stringify(form.toFhir(), null, 2)}</pre>
    </>
  );
}
PropTypeDescription
templateFormTemplate | stringInline template (object or JSON). Takes precedence over templateId.
templateIdstringTemplate to load from the API (needs apiKey or accessToken).
apiKey / accessTokenstringPublishable key (X-API-Key) or session token (Authorization: Bearer).
apiBasestringClara API. Default https://api.clara.care/api.
analysisId, live, liveFromstring, boolean, 'start' | 'tail'Live mode: the consultation to follow and where to start reading.
lang'es' | 'en'Language of the form texts.
value / onChange, defaultValuesFormValuesControlled mode, or initial values in uncontrolled mode.
onSubmit, onInvalid, onReady, onErrorcallbacksValid submission with { json, fhir, files }, errors by field, template ready, { code, message }.
lockedFieldsstring[]Fields the person cannot edit (live and programmatic values still apply).
submit, submitLabel, secondaryAction, autosaveoptionsAutomatic send to your server, button texts, draft button and periodic drafts.
widgetboolean | optionsBrings Clara Widget to the page (see below).
theme, loadFonts, showSource, idPrefixoptionslight | dark | auto, optional external font, the «From the sentence» line, id prefix for several forms.

Web component <clara-form>

The element renders in a Shadow DOM: your page's styles do not reach it and its own never leak. Attributes map to the props above; objects (template, defaultValues, widget options, submit headers) go through properties. Events are CustomEvents with bubbles and composed.

HTML
<script src="https://cdn.clara.care/form/latest.js"></script>
<clara-form template-id="TEMPLATE_ID" api-key="PUBLISHABLE_KEY" lang="en" theme="auto"></clara-form>
<script>
  const form = document.querySelector('clara-form');
  form.addEventListener('clara-submit', (e) => save(e.detail.fhir));
</script>
AttributeMeaning
template-id, api-key, access-token, api-baseTemplate and credentials, as in React.
templateJSON in the attribute; object or JSON in the property.
analysis-id, live, live-fromLive mode.
lang, theme, readonly, locked-fieldsLanguage, light | dark | auto, everything disabled, comma-separated locked fields.
submit-label, no-submit, submit-disabled, secondary-action, autosave-intervalButtons and drafts.
submit-url, submit-format, submit-include-files, submit-with-credentialsAutomatic send; headers only through the submitTarget property.
widgetBoolean in the attribute; options object in the property.
show-source="false", load-fontsHide «From the sentence»; load a font (true or URL).

Events (detail)

  • clara-ready { template }
  • clara-change { values, changes, fieldId, value, source }
  • clara-submit { values, json, fhir, files, templateId, analysisId } (only when valid)
  • clara-invalid { errors }
  • clara-secondary-action and clara-autosave: like clara-submit, without validating, fhir in-progress
  • clara-submitted { ok, status, response } and clara-submit-error { code, message, status?, response? }
  • clara-live-status { status } and clara-live-update { fieldId, value?, applied, reason?, provenance? }
  • clara-widget-ready { scriptUrl, created } and clara-widget-error { code, message }
  • clara-error { code, message, status? }

CDN script and manual init

The CDN script also starts on its own from the data-clara-* attributes of its tag, or manually with ClaraForm.init(config), which resolves with the API once the template is ready. By default it renders in the page's DOM with all styles scoped to .clara-form; shadow: true renders in a Shadow DOM.

HTML
<div id="clara-form-container"></div>
<script
  src="https://cdn.clara.care/form/latest.js"
  data-clara-template="TEMPLATE_ID"
  data-clara-api-key="PUBLISHABLE_KEY"
  data-clara-container="clara-form-container"
></script>
JavaScript
const api = await ClaraForm.init({
  templateId: 'TEMPLATE_ID', apiKey: 'PUBLISHABLE_KEY', containerId: 'clara-form-container',
  widget: true,
  submit: { url: 'https://your-server/visits', format: 'both' },
  onSubmit: (data, { fhir }) => {},
  onError: (error) => console.error(error.code, error.message),
});
api.getFormData(); api.setFieldValue('reason', 'Check-up'); api.toFhir(); api.destroy();

data-clara-* attributes

  • data-clara-template (or data-clara-template-id), data-clara-api-key, data-clara-container (id or #id / .class selector)
  • data-clara-lang, data-clara-read-only, data-clara-theme, data-clara-locked-fields, data-clara-load-fonts, data-clara-shadow
  • data-clara-api-base, data-clara-analysis-id, data-clara-live
  • data-clara-widget, data-clara-widget-script
  • data-clara-submit-url, data-clara-submit-format, data-clara-submit-include-files, data-clara-submit-with-credentials, data-clara-secondary-action

Form + widget

With widget the form itself brings Clara Widget (the floating voice assistant) to the page: one integration instead of two scripts. It loads it once from the same CDN that served the form, passes it apiKey, apiBase, templateId, analysisId, lang and the theme color, and destroys it on unmount only if it created it. If the form has no analysisId and the widget starts a consultation, the form hooks onto it.

The widget needs its own CSP permissions and runs with no interface inside an iframe; the form detects that and does not try to start it.

HTML
<clara-form template-id="TEMPLATE_ID" api-key="PUBLISHABLE_KEY" widget></clara-form>
<script>
  // Options (object) through the property; the attribute only turns it on.
  document.querySelector('clara-form').widget = { position: 'bottom-left', autoOpen: true };
</script>

Save and send

onSubmit and clara-submit give you the data. With submit the form also posts it to your server without extra code: format json (default), fhir (the QuestionnaireResponse as application/fhir+json) or both; multipart/form-data when includeFiles and files are attached; withCredentials to send your site's cookies. The button shows Sending, Sent or Retry, and the result is announced next to it.

Everything in headers travels in the browser: use a short-lived token or an endpoint that authenticates with cookies, never a server secret. Your endpoint needs CORS for the page origin and connect-src in your CSP. Values are health information: the form sends them only to that URL.

HTML
<clara-form template-id="TEMPLATE_ID" api-key="PUBLISHABLE_KEY"
  submit-url="https://your-server/visits" submit-format="both"
  secondary-action="Save draft" autosave-interval="15000"></clara-form>
<script>
  const form = document.querySelector('clara-form');
  form.submitTarget = { ...form.submitTarget, headers: { 'X-Clinic': 'c-1' } };
  form.addEventListener('clara-submitted', (e) => console.info(e.detail.status));
  form.addEventListener('clara-submit-error', (e) => console.warn(e.detail.code));
  form.addEventListener('clara-autosave', (e) => saveDraft(e.detail.values));
</script>

Live mode

With live and analysisId the form asks the API for a read token of the consultation stream, reads its records by server-sent events (from the start, catching up, or from the tail), renews the token and reconnects where it left off, applying no value twice. If a Clara Widget is on the page it also listens to its window events, and with live and no analysisId it waits for the widget to start a consultation.

The person wins: a field edited by hand is not overwritten by later live values (onLiveUpdate with applied false and reason manual_edit). Under each live value the form shows «From the sentence: …» when the record carries the source text. Requirements: a credential of the same user who owns the consultation, your origin registered, the consultation's template, and connect-src for the API and https://*.b.aws.s2.dev.

HTML
<clara-form template-id="TEMPLATE_ID" api-key="PUBLISHABLE_KEY" analysis-id="CONSULTATION_ID" live></clara-form>

Validation

required (empty text, unchecked box, empty odontogram, no files), pattern (as the HTML attribute: the whole value must match) and number (numeric, with min and max when the template has them). The message is the field's validationMessage or a default one in the form language. Errors show after leaving a field or on submit; onSubmit only runs when everything is valid, otherwise onInvalid and focus goes to the first field with an error. Outside React: validateValues(template, values, lang) and validateField(field, value, lang).

FHIR and JSON

toFhirQuestionnaireResponse(template, values, options) builds an R4 QuestionnaireResponse: one group item per section (linkId = section key) with one item per field (linkId = field key). Answers: valueString for text and textarea, valueDecimal for number, valueBoolean for checkbox, valueCoding for select, valueAttachment for file and valueString with the JSON list of actions for the odontogram. Unanswered questions are omitted unless includeEmpty is true. toLabeledJSON(template, values) returns { [key]: { label, type, section, sectionLabel, value } }.

TypeScript
import { toFhirQuestionnaireResponse, toLabeledJSON } from '@clara.care/form';

const qr = toFhirQuestionnaireResponse(template, values, {
  status: 'completed',
  subject: { reference: 'Patient/123' },
  encounter: { reference: 'Encounter/456' },
  questionnaire: 'https://your-server/Questionnaire/visit',
  codeSystem: 'https://your-server/CodeSystem/options',
});

Theme and styles

No external fonts by default: the form uses the system font unless you set loadFonts. CSS variables on any ancestor or on <clara-form> cross the Shadow DOM: --clara-form-primary (#2a4276), --clara-form-primary-contrast, --clara-form-font, --clara-form-radius (10px), --clara-form-bg, --clara-form-surface and -surface-alt, --clara-form-text, -heading and -muted, --clara-form-border, --clara-form-error, --clara-form-live, --clara-form-focus, --clara-form-input-bg and -disabled-bg. theme="dark" or "auto" switches the palette; every variable has a -dark twin. The odontogram stays light in both themes.

Stable classes in the light DOM: .clara-form, .clara-form-section, .clara-form-field, .clara-form-input, .clara-form-error, .clara-form-source, .clara-form-actions, .clara-form-submit (data-state idle | sending | sent | error), .clara-form-secondary and .clara-form-send-status. Inside <clara-form> the container is part="root".

CSS
clara-form {
  --clara-form-primary: #2a4276;
  --clara-form-radius: 8px;
  --clara-form-font: 'Work Sans', system-ui, sans-serif;
}

Accessibility

  • Every input has a <label for>; groups (odontogram, iframe) use aria-labelledby.
  • aria-required, aria-invalid and aria-describedby point at the error, the help text and the «From the sentence» line; errors use role="alert" and a summary on submit; the live status uses role="status".
  • The submit button carries aria-busy while sending; the result is announced next to it with role="status" (sent) or role="alert" (error).
  • Visible focus (:focus-visible).
  • Odontogram with a keyboard: every tooth is a button (Tab), Enter or Space marks the whole tooth with the selected condition, the menu key or Shift+F10 opens the tooth menu (focus moves in, Escape closes it). Individual surfaces remain mouse or touch only.

Content Security Policy

DirectiveValueFor
script-srchttps://cdn.clara.carethe form's CDN script and, with widget, the widget's
connect-srchttps://api.clara.caretemplates and the live-mode token (or your apiBase)
connect-srchttps://*.b.aws.s2.devlive mode (reading the stream)
connect-srcyour submit urlautomatic send of the submission
style-src'unsafe-inline'the form inserts its stylesheet as a <style> inside its container or shadow root
style-src / font-srchttps://fonts.googleapis.com / https://fonts.gstatic.comonly with loadFonts
frame-src, img-srcthe origins of your iframe fields and section iconsonly if the template uses them

Planning an integration?

Tell us about your system and your forms. We run small pilots with technology partners.

Cookie settings

Choose which optional cookies Clara Care may use. They stay off until you turn them on, and you can change your choice at any time from Cookie settings in the footer. Privacy policy