# Form

A form with consistent rhythm, sections with legends, side-by-side rows and a footer for its actions.

- Family: form
- Import: `import { Form, FormSection, FormRow, FormFooter } from "@senvenli/react/form";`
- Page: https://design.senvenli.com/docs/components/form
- JSON: https://design.senvenli.com/docs/components/form.json

## Example: A small form

Sections with legends, a row of two fields, and one primary action in the footer.

```tsx
import { Button } from "@senvenli/react/action";
import { Form, FormFooter, FormRow, FormSection, Input, TextArea } from "@senvenli/react/form";

export default function Example() {
  return (
    <Form onSubmit={(event) => event.preventDefault()}>
      <FormSection legend="Contact">
        <FormRow>
          <Input label="First name" name="firstName" autoComplete="given-name" defaultValue="Ada" isRequired />
          <Input label="Last name" name="lastName" autoComplete="family-name" defaultValue="Lovelace" isRequired />
        </FormRow>
        <Input label="Email" name="email" type="email" autoComplete="email" isRequired />
        <Input type="tel" label="Phone" name="phone" defaultCountry="US" suggestedCountries={["US", "CA", "GB"]} />
      </FormSection>
      <FormSection legend="Billing">
        <Input label="Company" name="company" autoComplete="organization" />
        <TextArea label="Notes" name="notes" maxLength={200} />
      </FormSection>
      <FormFooter>
        <Button type="reset" variant="subtle">Cancel</Button>
        <Button type="submit" variant="primary">Add customer</Button>
      </FormFooter>
    </Form>
  );
}
```

## Examples

### Validation on submit

An invalid field takes focus and `onSubmit` is not called; entered values are kept.

```tsx
import { Button } from "@senvenli/react/action";
import { Banner } from "@senvenli/react/feedback";
import { Form, FormFooter, Input } from "@senvenli/react/form";
import { Stack } from "@senvenli/react/layout";
import { useState } from "react";

export default function Example() {
  const [project, setProject] = useState<string | null>(null);
  return (
    <Stack space="space-300">
      {project && <Banner tone="success" title={`${project} was created`} onDismiss={() => setProject(null)} />}
      <Form
        onSubmit={(event) => {
          event.preventDefault();
          setProject(String(new FormData(event.currentTarget).get("name")));
        }}
      >
        <Input
          label="Project name"
          name="name"
          isRequired
          validate={(value) => (value.trim().length < 3 ? "Use at least 3 characters, so the team can tell projects apart." : null)}
        />
        <Input label="Client email" name="email" type="email" isRequired errorMessage="Enter a valid email: name@example.com" />
        <Input type="number" label="Budget" name="budget" currency="USD" minValue={0} isOptional />
        <FormFooter>
          <Button type="submit" variant="primary">Create project</Button>
        </FormFooter>
      </Form>
    </Stack>
  );
}
```

### Server errors

`validationErrors` marks fields by name until the person edits them.

```tsx
import { Button } from "@senvenli/react/action";
import { Form, FormFooter, Input } from "@senvenli/react/form";
import { useState } from "react";

const TAKEN = "ada@example.com";

export default function Example() {
  const [errors, setErrors] = useState<Record<string, string>>({});
  return (
    <Form
      validationErrors={errors}
      onSubmit={(event) => {
        event.preventDefault();
        // Stands in for the server's answer.
        const email = new FormData(event.currentTarget).get("email");
        setErrors(email === TAKEN ? { email: "That email already has an account. Sign in or use another one." } : {});
      }}
    >
      <Input label="Full name" name="name" autoComplete="name" defaultValue="Ada Lovelace" isRequired />
      <Input label="Email" name="email" type="email" autoComplete="email" defaultValue={TAKEN} isRequired />
      <FormFooter>
        <Button type="submit" variant="primary">Send invite</Button>
      </FormFooter>
    </Form>
  );
}
```

## Guidelines

### When to use it

- Collecting input that is submitted together.

### Use something else when

- [field](https://design.senvenli.com/docs/components/field.md): One control needs a label, hint and error row outside a form.
- [dialog](https://design.senvenli.com/docs/components/dialog.md): The form is a short focused task over the page.

### Do and avoid

- One primary submit button in the FormFooter.
- Mark the exception: required when most fields are optional, optional when most are required.

## Accessibility

Keyboard:

- Enter: Submits the form from a text field.

Built in:

- On submit, focus moves to the first invalid field.
- FormSection is a fieldset named by its legend.

You provide:

- A legend for each FormSection.

## API reference

### Form

| Prop | Type | Default | Required | Description |
| --- | --- | --- | --- | --- |
| width | `"full" \| "narrow"` | `"narrow"` | no | `narrow` (default) caps single-column forms at 560px. |

Behavior props from React Aria:

| Prop | Type | Default | Required | Description |
| --- | --- | --- | --- | --- |
| role | `"search" \| "presentation"` |  | no | An ARIA role override to apply to the form element. |
| autoCapitalize | `"off" \| "none" \| "on" \| "sentences" \| "words" \| "characters"` |  | no | Controls whether inputted text is automatically capitalized and, if so, in what manner. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/autocapitalize). |
| onReset | `(event: FormEvent<HTMLFormElement>) => void` |  | no | Triggered when a user resets the form. |
| onSubmit | `(event: FormEvent<HTMLFormElement>) => void` |  | no | Triggered when a user submits the form. |
| onInvalid | `(event: FormEvent<HTMLFormElement>) => void` |  | no | Triggered for each invalid field when a user submits the form. |
| target | `"_self" \| "_blank" \| "_parent" \| "_top"` |  | no | The target attribute specifies a name or a keyword that indicates where to display the response that is received after submitting the form. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#target). |
| validationBehavior | `"aria" \| "native"` | `"aria"` | no | Whether to use native HTML form validation to prevent form submission when a field value is missing or invalid, or mark fields as required or invalid via ARIA. |
| validationErrors | `ValidationErrors` |  | no | Validation errors for the form, typically returned by a server. This should be set to an object mapping from input names to errors. |
| action | `string \| ((formData: FormData) => void \| Promise<void>)` |  | no | Where to send the form-data when the form is submitted. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#action). |
| encType | `"application/x-www-form-urlencoded" \| "multipart/form-data" \| "text/plain"` |  | no | The enctype attribute specifies how the form-data should be encoded when submitting it to the server. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#enctype). |
| method | `"dialog" \| "get" \| "post"` |  | no | The HTTP method to submit the form with. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#method). |
| autoComplete | `"off" \| "on"` |  | no | Indicates whether input elements can by default have their values automatically completed by the browser. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#autocomplete). |

Also takes 77 standard DOM and ARIA attributes (id, aria-label, event handlers…).

### FormSection

| Prop | Type | Default | Required | Description |
| --- | --- | --- | --- | --- |
| legend | `React.ReactNode` |  | yes | The section title (`heading-small`). |
| children | `React.ReactNode` |  | yes |  |
| isDisabled | `boolean` |  | no |  |

### FormRow

| Prop | Type | Default | Required | Description |
| --- | --- | --- | --- | --- |
| children | `React.ReactNode` |  | yes |  |

### FormFooter

| Prop | Type | Default | Required | Description |
| --- | --- | --- | --- | --- |
| children | `React.ReactNode` |  | yes |  |

### Tokens it reads

`--ds-border`, `--ds-space-100`, `--ds-space-200`, `--ds-space-300`, `--ds-text`

## Related

- [field](https://design.senvenli.com/docs/components/field.md)
- [input](https://design.senvenli.com/docs/components/input.md)
- [button](https://design.senvenli.com/docs/components/button.md)
