# Form (/components/form)

<ReferenceLinks
  links={[
    { label: "Source", href: meta.links.source, iconName: "code" },
    { label: "Stories", href: meta.links.stories },
  ]}
/>

<Stage code={"<Form.Section>\n  <Form.Field\n    label=\"Entity type name\"\n    description=\"Shown in search results and the type editor.\"\n    required\n  >\n    <TextInput\n      name=\"entityTypeName\"\n      width=\"md\"\n      value=\"Research paper\"\n      onChange={() => {}}\n    />\n  </Form.Field>\n  <Form.Field layout=\"inline\" label=\"Publish to type registry\">\n    <Toggle name=\"publishToRegistry\" value={true} onChange={() => {}} />\n  </Form.Field>\n</Form.Section>"}>
  <FormSection>
    <FormField
      label="Entity type name"
      description="Shown in search results and the type editor."
      required
    >
      <DemoState>
        <TextInput
          name="entityTypeName"
          width="md"
          value="Research paper"
          onChange={noop}
        />
      </DemoState>
    </FormField>
    <FormField layout="inline" label="Publish to type registry">
      <DemoState>
        <Toggle name="publishToRegistry" value={true} onChange={noop} />
      </DemoState>
    </FormField>
  </FormSection>
</Stage>

## Installation [#installation]

1. Install the package.

```sh
npm install @hashintel/ds-components
```

2. Import the component.

```tsx
import { useState } from "react";

import { Form, TextInput } from "@hashintel/ds-components";

export const EntityNameField = () => {
  const [name, setName] = useState("");

  return (
    <Form.Field label="Entity name" required>
      <TextInput name="entityName" value={name} onChange={setName} required />
    </Form.Field>
  );
};
```

### When to use [#when-to-use]

<DoList
  items={[
    "Wrap every input in a Form.Field — it supplies the label, description and error display, and wires the label to the input automatically.",
    <Fragment key="0">
      Use <code>layout="inline"</code> fields inside a Form.Section for settings
      panels, so labels and inputs align across fields.
    </Fragment>,
    "Use Form.Row for values entered as a pair, such as minimum/maximum limits or first/last name.",
    <Fragment key="1">
      Use <code>as="legend"</code> when the field wraps a group of inputs such
      as RadioGroup or CheckboxGroup.
    </Fragment>,
  ]}
/>

### When not to use [#when-not-to-use]

<DontList
  items={[
    <Fragment key="0">
      Don't put two inputs in one Form.Field — it labels exactly one control.
      Use Form.Row for side-by-side fields, or <code>as="legend"</code> for
      groups.
    </Fragment>,
    <Fragment key="1">
      Don't use a placeholder instead of a label — it disappears as soon as a
      value is entered. Use <code>hideLabel</code> to hide the label visually.
    </Fragment>,
    "Don't wrap controls that already label themselves, such as a Checkbox or Toggle with its own label text.",
    "Don't build multi-column forms out of Form.Row — a single column reads faster. Reserve rows for naturally paired values.",
  ]}
/>

## Anatomy [#anatomy]

`Form.Field` renders its label, description and error parts from props; you only compose the structural parts.

```tsx
<Form.Section>
  <Form.Field
    label="Name" // renders Form.Field.Label
    description="Helper text" // renders Form.Field.Description
    errors={["Error message"]} // renders Form.Field.Errors
  >
    {/* exactly one input */}
  </Form.Field>

  <Form.Row>
    <Form.Field label="Minimum">{/* input */}</Form.Field>
    <Form.Field label="Maximum">{/* input */}</Form.Field>
  </Form.Row>
</Form.Section>
```

## Examples [#examples]

### Basic [#basic]

A field needs only a `label` and a single input child — the label is associated with the input automatically, no ids required.

<Stage code={"<Form.Field label=\"Workspace name\">\n  <TextInput\n    name=\"workspaceName\"\n    width=\"md\"\n    value=\"Ontology research\"\n    onChange={() => {}}\n  />\n</Form.Field>"}>
  <FormField label="Workspace name">
    <DemoState>
      <TextInput
        name="workspaceName"
        width="md"
        value="Ontology research"
        onChange={noop}
      />
    </DemoState>
  </FormField>
</Stage>

### Required [#required]

`required` adds the mark to the label only — it never reaches the input. Set `required` on the input too so forms and assistive technology enforce it.

<Stage code={"<Form.Field label=\"Teammate email\" required>\n  <TextInput\n    name=\"teammateEmail\"\n    type=\"email\"\n    width=\"md\"\n    value=\"elena@hash.ai\"\n    onChange={() => {}}\n    required\n  />\n</Form.Field>"}>
  <FormField label="Teammate email" required>
    <DemoState>
      <TextInput
        name="teammateEmail"
        type="email"
        width="md"
        value="elena@hash.ai"
        onChange={noop}
        required
      />
    </DemoState>
  </FormField>
</Stage>

### Disabled [#disabled]

`disabled` greys the field's label, description and errors; disable the input separately — the prop doesn't cascade.

<Stage code={"<Form.Field\n  label=\"Entity ID\"\n  description=\"Assigned when the entity is created.\"\n  disabled\n>\n  <TextInput\n    name=\"entityId\"\n    width=\"md\"\n    value=\"e7f2a49c-3b1d-4e08\"\n    onChange={() => {}}\n    disabled\n  />\n</Form.Field>"}>
  <FormField
    label="Entity ID"
    description="Assigned when the entity is created."
    disabled
  >
    <TextInput
      name="entityId"
      width="md"
      value="e7f2a49c-3b1d-4e08"
      onChange={noop}
      disabled
    />
  </FormField>
</Stage>

### Descriptions [#descriptions]

`description` renders between the label and the input; `descriptionBottom` renders after it. Use them for format hints and consequences, not to restate the label.

<Stage code={"<Form.Field\n  label=\"Entity label\"\n  description=\"Shown wherever the entity is referenced.\"\n>\n  <TextInput name=\"entityLabel\" width=\"md\" value=\"\" onChange={() => {}} />\n</Form.Field>\n<Form.Field\n  label=\"API key name\"\n  descriptionBottom=\"You can't change this later.\"\n>\n  <TextInput name=\"apiKeyName\" width=\"md\" value=\"\" onChange={() => {}} />\n</Form.Field>"}>
  <FormField
    label="Entity label"
    description="Shown wherever the entity is referenced."
  >
    <DemoState>
      <TextInput name="entityLabel" width="md" value="" onChange={noop} />
    </DemoState>
  </FormField>
  <FormField
    label="API key name"
    descriptionBottom="You can't change this later."
  >
    <DemoState>
      <TextInput name="apiKeyName" width="md" value="" onChange={noop} />
    </DemoState>
  </FormField>
</Stage>

### Errors [#errors]

Pass `errors` as an array — one message renders inline, several render as a list, and they're announced when they appear. Set `invalid` on the input yourself; the field never modifies its children.

<Stage code={"<Form.Field\n  label=\"Entity type URL\"\n  errors={[\"Enter a URL that starts with https://\"]}\n>\n  <TextInput\n    name=\"entityTypeUrl\"\n    width=\"md\"\n    value=\"example.com/types/person\"\n    onChange={() => {}}\n    invalid\n  />\n</Form.Field>\n<Form.Field\n  label=\"Property name\"\n  errors={[\"Enter a property name\", \"Property names must be unique\"]}\n>\n  <TextInput\n    name=\"propertyName\"\n    width=\"md\"\n    value=\"\"\n    onChange={() => {}}\n    invalid\n  />\n</Form.Field>"}>
  <FormField
    label="Entity type URL"
    errors={["Enter a URL that starts with https://"]}
  >
    <DemoState>
      <TextInput
        name="entityTypeUrl"
        width="md"
        value="example.com/types/person"
        onChange={noop}
        invalid
      />
    </DemoState>
  </FormField>
  <FormField
    label="Property name"
    errors={["Enter a property name", "Property names must be unique"]}
  >
    <DemoState>
      <TextInput
        name="propertyName"
        width="md"
        value=""
        onChange={noop}
        invalid
      />
    </DemoState>
  </FormField>
</Stage>

### Hidden label [#hidden-label]

Every field needs a label. When the context makes a visible one redundant — a lone search input, a table cell — set `hideLabel` so it stays announced to screen readers.

<Stage code={"<Form.Field label=\"Search entities\" hideLabel>\n  <TextInput\n    name=\"searchEntities\"\n    width=\"md\"\n    value=\"\"\n    placeholder=\"Search entities…\"\n    onChange={() => {}}\n  />\n</Form.Field>"}>
  <FormField label="Search entities" hideLabel>
    <DemoState>
      <TextInput
        name="searchEntities"
        width="md"
        value=""
        placeholder="Search entities…"
        onChange={noop}
      />
    </DemoState>
  </FormField>
</Stage>

### Label tooltip and actions [#label-tooltip-and-actions]

`labelTooltip` adds a help icon after the label; `labelActions` puts controls at the far end of the label row (next to the input in inline layout). Both sit outside the `<label>`, so clicking them doesn't focus the input.

<Stage code={"<Form.Field\n  label=\"Inference model\"\n  labelTooltip=\"Used by flows that infer entities from the web.\"\n>\n  <TextInput\n    name=\"inferenceModel\"\n    width=\"md\"\n    value=\"Default (automatic)\"\n    onChange={() => {}}\n  />\n</Form.Field>\n<Form.Field\n  label=\"Webhook URL\"\n  labelActions={\n    <Button variant=\"ghost\" size=\"xs\">\n      Send test\n    </Button>\n  }\n>\n  <TextInput\n    name=\"webhookUrl\"\n    width=\"md\"\n    value=\"https://api.example.com/hooks/runs\"\n    onChange={() => {}}\n  />\n</Form.Field>"}>
  <FormField
    label="Inference model"
    labelTooltip="Used by flows that infer entities from the web."
  >
    <DemoState>
      <TextInput
        name="inferenceModel"
        width="md"
        value="Default (automatic)"
        onChange={noop}
      />
    </DemoState>
  </FormField>
  <FormField
    label="Webhook URL"
    labelActions={
      <Button variant="ghost" size="xs">
        Send test
      </Button>
    }
  >
    <DemoState>
      <TextInput
        name="webhookUrl"
        width="md"
        value="https://api.example.com/hooks/runs"
        onChange={noop}
      />
    </DemoState>
  </FormField>
</Stage>

### Sizes [#sizes]

`size` scales the label, description and error text — set the same size on the field and its input. `md` is the default.

<Stage code={"<Form.Field size=\"xxs\" label=\"xxs\">\n  <TextInput\n    name=\"sizeXxs\"\n    size=\"xxs\"\n    width=\"sm\"\n    value=\"\"\n    placeholder=\"Entity label\"\n    onChange={() => {}}\n  />\n</Form.Field>\n<Form.Field size=\"xs\" label=\"xs\">\n  <TextInput\n    name=\"sizeXs\"\n    size=\"xs\"\n    width=\"sm\"\n    value=\"\"\n    placeholder=\"Entity label\"\n    onChange={() => {}}\n  />\n</Form.Field>\n<Form.Field size=\"sm\" label=\"sm\">\n  <TextInput\n    name=\"sizeSm\"\n    size=\"sm\"\n    width=\"sm\"\n    value=\"\"\n    placeholder=\"Entity label\"\n    onChange={() => {}}\n  />\n</Form.Field>\n<Form.Field size=\"md\" label=\"md\">\n  <TextInput\n    name=\"sizeMd\"\n    size=\"md\"\n    width=\"sm\"\n    value=\"\"\n    placeholder=\"Entity label\"\n    onChange={() => {}}\n  />\n</Form.Field>\n<Form.Field size=\"lg\" label=\"lg\">\n  <TextInput\n    name=\"sizeLg\"\n    size=\"lg\"\n    width=\"sm\"\n    value=\"\"\n    placeholder=\"Entity label\"\n    onChange={() => {}}\n  />\n</Form.Field>"}>
  <FormField size="xxs" label="xxs">
    <DemoState>
      <TextInput
        name="sizeXxs"
        size="xxs"
        width="sm"
        value=""
        placeholder="Entity label"
        onChange={noop}
      />
    </DemoState>
  </FormField>
  <FormField size="xs" label="xs">
    <DemoState>
      <TextInput
        name="sizeXs"
        size="xs"
        width="sm"
        value=""
        placeholder="Entity label"
        onChange={noop}
      />
    </DemoState>
  </FormField>
  <FormField size="sm" label="sm">
    <DemoState>
      <TextInput
        name="sizeSm"
        size="sm"
        width="sm"
        value=""
        placeholder="Entity label"
        onChange={noop}
      />
    </DemoState>
  </FormField>
  <FormField size="md" label="md">
    <DemoState>
      <TextInput
        name="sizeMd"
        size="md"
        width="sm"
        value=""
        placeholder="Entity label"
        onChange={noop}
      />
    </DemoState>
  </FormField>
  <FormField size="lg" label="lg">
    <DemoState>
      <TextInput
        name="sizeLg"
        size="lg"
        width="sm"
        value=""
        placeholder="Entity label"
        onChange={noop}
      />
    </DemoState>
  </FormField>
</Stage>

### Inline layout [#inline-layout]

`layout="inline"` places the label and input on one line — the settings-panel arrangement. `inputAlign="end"` pushes the input to the far edge of the row, and `labelDirection="right"` puts the label after the input instead — the trailing-label pattern.

<Stage code={"<div style={{ width: 420 }}>\n  <Form.Section>\n    <Form.Field\n      layout=\"inline\"\n      inputAlign=\"start\"\n      label=\"Enable AI inference\"\n    >\n      <Toggle name=\"aiInference\" value={true} onChange={() => {}} />\n    </Form.Field>\n    <Form.Field\n      layout=\"inline\"\n      inputAlign=\"end\"\n      label=\"Publish entity history\"\n    >\n      <Toggle name=\"entityHistory\" value={false} onChange={() => {}} />\n    </Form.Field>\n    <Form.Field\n      layout=\"inline\"\n      labelDirection=\"right\"\n      label=\"Autosave drafts\"\n    >\n      <Toggle name=\"autosaveDrafts\" value={true} onChange={() => {}} />\n    </Form.Field>\n  </Form.Section>\n</div>"}>
  <div style={{ width: 420 }}>
    <FormSection>
      <FormField
        layout="inline"
        inputAlign="start"
        label="Enable AI inference"
      >
        <DemoState>
          <Toggle name="aiInference" value={true} onChange={noop} />
        </DemoState>
      </FormField>
      <FormField
        layout="inline"
        inputAlign="end"
        label="Publish entity history"
      >
        <DemoState>
          <Toggle name="entityHistory" value={false} onChange={noop} />
        </DemoState>
      </FormField>
      <FormField
        layout="inline"
        labelDirection="right"
        label="Autosave drafts"
      >
        <DemoState>
          <Toggle name="autosaveDrafts" value={true} onChange={noop} />
        </DemoState>
      </FormField>
    </FormSection>
  </div>
</Stage>

### Grouping related inputs [#grouping-related-inputs]

A `<label>` can name only one control. When the field wraps a group — RadioGroup, CheckboxGroup — set `as="legend"` so the whole group is named with fieldset semantics.

<Stage code={"<Form.Field\n  as=\"legend\"\n  label=\"Entity visibility\"\n  description=\"Who can see entities created by this flow.\"\n>\n  <RadioGroup\n    name=\"visibility\"\n    items={[\n      { value: \"private\", label: \"Only me\" },\n      { value: \"workspace\", label: \"Everyone in the workspace\" },\n      { value: \"public\", label: \"Public\" },\n    ]}\n    value=\"workspace\"\n    onChange={() => {}}\n  />\n</Form.Field>"}>
  <FormField
    as="legend"
    label="Entity visibility"
    description="Who can see entities created by this flow."
  >
    <DemoState>
      <RadioGroup
        name="visibility"
        items={[
          { value: "private", label: "Only me" },
          { value: "workspace", label: "Everyone in the workspace" },
          { value: "public", label: "Public" },
        ]}
        value="workspace"
        onChange={noop}
      />
    </DemoState>
  </FormField>
</Stage>

### Rows [#rows]

`Form.Row` places fields side by side, sharing the row's width and bottom-aligned so inputs line up; `gap` controls the spacing. For a message that belongs to the pair rather than one field, pass a `Form.Field.Errors` element to `errors` — it renders below the whole row.

<Stage code={"<div style={{ width: 560 }}>\n  <Form.Row\n    gap=\"md\"\n    errors={\n      <Form.Field.Errors errors={[\"Maximum must be at least the minimum\"]} />\n    }\n  >\n    <Form.Field label=\"Minimum instances\">\n      <NumberInput\n        name=\"minInstances\"\n        value={10}\n        onChange={() => {}}\n        invalid\n      />\n    </Form.Field>\n    <Form.Field label=\"Maximum instances\">\n      <NumberInput\n        name=\"maxInstances\"\n        value={1}\n        onChange={() => {}}\n        invalid\n      />\n    </Form.Field>\n  </Form.Row>\n</div>"}>
  <div style={{ width: 560 }}>
    <FormRow
      gap="md"
      errors={
        <FormFieldErrors errors={["Maximum must be at least the minimum"]} />
      }
    >
      <FormField label="Minimum instances">
        <DemoState>
          <NumberInput
            name="minInstances"
            value={10}
            onChange={noop}
            invalid
          />
        </DemoState>
      </FormField>
      <FormField label="Maximum instances">
        <DemoState>
          <NumberInput
            name="maxInstances"
            value={1}
            onChange={noop}
            invalid
          />
        </DemoState>
      </FormField>
    </FormRow>
  </div>
</Stage>

### Sections [#sections]

`Form.Section` aligns inline fields onto a shared grid — labels and inputs each share a column across fields — and spaces adjacent fields automatically.

<Stage code={"<Form.Section>\n  <Form.Field layout=\"inline\" label=\"Workspace name\">\n    <TextInput\n      name=\"workspaceName\"\n      width=\"sm\"\n      value=\"Ontology research\"\n      onChange={() => {}}\n    />\n  </Form.Field>\n  <Form.Field layout=\"inline\" label=\"Snapshot retention (days)\" required>\n    <NumberInput\n      name=\"snapshotRetention\"\n      width=\"xs\"\n      value={30}\n      onChange={() => {}}\n    />\n  </Form.Field>\n  <Form.Field layout=\"inline\" label=\"Public access\">\n    <Toggle name=\"publicAccess\" value={false} onChange={() => {}} />\n  </Form.Field>\n</Form.Section>"}>
  <FormSection>
    <FormField layout="inline" label="Workspace name">
      <DemoState>
        <TextInput
          name="workspaceName"
          width="sm"
          value="Ontology research"
          onChange={noop}
        />
      </DemoState>
    </FormField>
    <FormField layout="inline" label="Snapshot retention (days)" required>
      <DemoState>
        <NumberInput
          name="snapshotRetention"
          width="xs"
          value={30}
          onChange={noop}
        />
      </DemoState>
    </FormField>
    <FormField layout="inline" label="Public access">
      <DemoState>
        <Toggle name="publicAccess" value={false} onChange={noop} />
      </DemoState>
    </FormField>
  </FormSection>
</Stage>

### Custom inputs [#custom-inputs]

Every input picks up the field's generated id automatically. A hand-rolled input must read `useFieldId` and set it as its `id`.

```tsx
import { useState } from "react";

import { Form, useFieldId } from "@hashintel/ds-components";

const ColorInput = ({
  value,
  onChange,
}: {
  value: string;
  onChange: (value: string) => void;
}) => {
  const id = useFieldId();
  return (
    <input
      type="color"
      id={id ?? undefined}
      value={value}
      onChange={(event) => onChange(event.target.value)}
    />
  );
};

export const AccentColorField = () => {
  const [color, setColor] = useState("#0775e3");

  return (
    <Form.Field label="Accent color">
      <ColorInput value={color} onChange={setColor} />
    </Form.Field>
  );
};
```

### Form libraries [#form-libraries]

`Form.Field` is driven entirely by props, so it drops into any form library. With TanStack Form, bind the label and errors once in a shared field component; in a real app the contexts and field components live in one module that every form imports.

```tsx
import { createFormHook, createFormHookContexts } from "@tanstack/react-form";

import { Form, TextInput } from "@hashintel/ds-components";

const { fieldContext, formContext, useFieldContext } = createFormHookContexts();

const TextField = ({
  label,
  required,
}: {
  label: string;
  required?: boolean;
}) => {
  const field = useFieldContext<string>();

  return (
    <Form.Field
      label={label}
      required={required}
      errors={field.state.meta.errors}
    >
      <TextInput
        name={field.name}
        value={field.state.value}
        onChange={(value) => field.handleChange(value)}
        onBlur={field.handleBlur}
        required={required}
        invalid={field.state.meta.errors.length > 0}
      />
    </Form.Field>
  );
};

const { useAppForm } = createFormHook({
  fieldComponents: { TextField },
  formComponents: {},
  fieldContext,
  formContext,
});

export const InviteTeammateForm = () => {
  const form = useAppForm({
    defaultValues: { email: "" },
    onSubmit: ({ value }) => console.log(value),
  });

  return (
    <form
      onSubmit={(event) => {
        event.preventDefault();
        void form.handleSubmit();
      }}
    >
      <form.AppField
        name="email"
        validators={{
          onChange: ({ value }) =>
            /^\S+@\S+\.\S+$/.test(value)
              ? undefined
              : "Enter a valid email address",
        }}
      >
        {(field) => <field.TextField label="Teammate email" required />}
      </form.AppField>
    </form>
  );
};
```

## Behavior [#behavior]

- Nothing is injected into children: the field talks to its input only through the generated label id. Set `size`, `disabled`, `required` and `invalid` on the input yourself.
- With `as="legend"` the generated id is not provided to children — group inputs label their own options.

## Content [#content]

- Labels name the data, 1–3 words, sentence case, no trailing punctuation: "Entity type name", "Teammate email".
- Write errors as instructions that reuse the label's words: "Enter an entity type name", "Maximum must be at least the minimum". Avoid "please", "sorry" and the word "invalid".
- Mark required fields consistently: if one required field carries the mark, they all should.

## Accessibility [#accessibility]

Form fields build on native `<fieldset>`, `<label>` and `<legend>` semantics — see the [WAI forms tutorial](https://www.w3.org/WAI/tutorials/forms/) for the underlying model.

### What Form provides [#what-form-provides]

- `Form.Field` renders a real `<fieldset>` and wires its `<label>` to the input through a generated id every ds-components input adopts automatically.
- `as="legend"` names the whole group, keeping the required mark and tooltip out of the group's accessible name.
- `hideLabel` hides the label visually but keeps it announced.
- Error messages render with `role="alert"`, so they're announced when they appear.

### What you must do [#what-you-must-do]

- Always pass a `label` — use `hideLabel` rather than leaving it empty or relying on a placeholder.
- Set `as="legend"` when the field wraps more than one input (RadioGroup, CheckboxGroup) — a label can name only one control.
- Mirror field state on the input: `invalid` when passing `errors`, and `disabled`/`required` on both.
- Give custom inputs the `useFieldId` id (see [Custom inputs](#custom-inputs)); without it the label is not associated.

## API reference [#api-reference]

### Form.Field [#formfield]

<PropsTable
  of={FormField}
  defaults={{
    as: '"label"',
    size: '"md"',
    labelDirection: '"left"',
    layout: '"block"',
    inputAlign: '"start"',
  }}
/>

### Form.Field.Label [#formfieldlabel]

<PropsTable
  of={FormFieldLabel}
  defaults={{
    as: '"label"',
    size: '"md"',
    direction: '"left"',
  }}
/>

### Form.Field.Description [#formfielddescription]

<PropsTable
  of={FormFieldDescription}
  defaults={{
    size: '"md"',
    direction: '"left"',
  }}
/>

### Form.Field.Errors [#formfielderrors]

<PropsTable of={FormFieldErrors} />

### Form.Row [#formrow]

<PropsTable
  of={FormRow}
  defaults={{
    gap: '"md"',
    align: '"bottom"',
    noWrap: "false",
  }}
/>

### Form.Section [#formsection]

<PropsTable of={FormSection} />

### useFieldId [#usefieldid]

Returns the id the nearest `Form.Field` provides for its input, or `null` when the component isn't rendered inside one.

```tsx
const fieldId: string | null = useFieldId();
```
