# Search field API

> Explore the API of Cimpress UI's search field component.

Source: https://ui.cimpress.io/components/search-field/api/

## Import

```tsx
import { SearchField } from '@cimpress-ui/react';
```

## Controlled/uncontrolled usage

```tsx
import { SearchField, Stack } from '@cimpress-ui/react';
import { useState } from 'react';

export default function Demo() {
  const [query, setQuery] = useState('checkbox');

  return (
    <Stack gap={32}>
      <SearchField label="Search (controlled)" value={query} onChange={setQuery} />
      <SearchField label="Search (uncontrolled)" defaultValue="checkbox" />
    </Stack>
  );
}
```

## Imperative API

```tsx
import { Button, SearchField, type SearchFieldApi, Stack } from '@cimpress-ui/react';
import { useRef } from 'react';

export default function Demo() {
  const apiRef = useRef<SearchFieldApi>(null);

  return (
    <Stack gap={16}>
      <SearchField label="Search" defaultValue="checkbox" apiRef={apiRef} />

      <Stack gap={16} direction={{ md: 'horizontal' }}>
        <Button onPress={() => apiRef.current?.focus()}>Focus</Button>
        <Button onPress={() => apiRef.current?.select()}>Select text</Button>
      </Stack>
    </Stack>
  );
}
```

## Accessibility notes

The search term can be submitted by pressing the Enter key, and cleared by pressing the Escape key.

`SearchField` requires a textual label to remain accessible to assistive technologies. See our [accessibility guide](/dev-guides/accessibility#labelling) for more details.

## Detecting changes

`SearchField` exposes multiple events that can be used to detect changes:

- `onChange` - triggered on every change of the field's value
- `onSubmit` - triggered when the value is submitted by the user (for example, by pressing the Enter key)
- `onClear` - triggered when the value is cleared by the user (for example, by pressing the clear button)

Play with the example below to see the difference between these events.

```tsx
import { SearchField, Stack, Text } from '@cimpress-ui/react';
import { useState } from 'react';

export default function Demo() {
  const [query, setQuery] = useState('');
  const [submittedQuery, setSubmittedQuery] = useState('');

  return (
    <Stack gap={16}>
      <SearchField
        label="Search"
        value={query}
        onChange={setQuery}
        onSubmit={setSubmittedQuery}
        onClear={() => setQuery('')}
      />
      <Text as="p">Current query: {query}</Text>
      <Text as="p">Submitted query: {submittedQuery}</Text>
    </Stack>
  );
}
```

## Forms

Search field can integrate with native HTML forms. See our [forms guide](/dev-guides/forms) to learn how to work with forms.

## API reference

### SearchField

Allows users to enter and clear a search query.

See [search field usage guidelines](https://ui.cimpress.io/components/search-field/).

- `ref`: `Ref<HTMLDivElement>`

  The `ref` type for this component.

**Props: `SearchFieldProps`**

- `id`: `string`

  The element's unique identifier. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id).

- `data-cim-style-root`: `boolean`

  Use this attribute to "claim" the component tree for exclusive Cimpress UI usage.

- `UNSAFE_className`: `string`

  Sets the CSS className for the element. Only use as a **last resort**. Use style props instead.

  See [styling guide](https://ui.cimpress.io/dev-guides/styling/).

- `UNSAFE_style`: `CSSProperties`

  Sets the CSS style for the element. Only use as a **last resort**. Use style props instead.

  See [styling guide](https://ui.cimpress.io/dev-guides/styling/).

- `label`: `string`

  The content to display as the label.

- `aria-label`: `string`

  Defines a string value that labels the current element.

- `aria-labelledby`: `string`

  Identifies the element (or elements) that labels the current element.

- `aria-describedby`: `string`

  Identifies the element (or elements) that describes the object.

- `aria-details`: `string`

  Identifies the element (or elements) that provide a detailed, extended description for the object.

- `form`: `string`

  The `<form>` element to associate the input with.
  The value of this attribute must be the id of a `<form>` in the same document.
  See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/input#form).

- `name`: `string`

  The name of the input element, used when submitting an HTML form. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/input#name).

- `description`: `string`

  A description for the field. Provides a hint such as specific requirements for what to choose.

- `error`: `FieldError`

  An error message for the field.

- `validate`: `(value: string) => string | true | string[] | undefined`

  A function that returns an error message (or `true`) if a given value is invalid.
  Validation errors are displayed to the user when the form is submitted.
  For real-time validation, use the `error` prop instead.

- `placeholder`: `string`

  The placeholder text displayed in the input field.

- `apiRef`: `RefObject<SearchFieldApi | null>`

  A React ref that allows access to the imperative API of this component.

- `autoComplete`: `string`

  Describes the type of autocomplete functionality the input should provide if any. See
  [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#htmlattrdefautocomplete).

- `maxLength`: `number`

  The maximum number of characters supported by the input. See
  [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#htmlattrdefmaxlength).

- `minLength`: `number`

  The minimum number of characters required by the input. See
  [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#htmlattrdefminlength).

- `pattern`: `string`

  Regex pattern that the value of the input must match to be valid. See
  [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#htmlattrdefpattern).

- `inputMode`: `'search' | 'none' | 'text' | 'tel' | 'url' | 'email' | 'numeric' | 'decimal'`

  Hints at the type of data that might be entered by the user while editing the element or its
  contents. See
  [MDN](https://html.spec.whatwg.org/multipage/interaction.html#input-modalities:-the-inputmode-attribute).

- `autoCorrect`: `string`

  An attribute that takes as its value a space-separated string that describes what, if any, type
  of autocomplete functionality the input should provide. See
  [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#autocomplete).

- `spellCheck`: `string`

  An enumerated attribute that defines whether the element may be checked for spelling errors.
  See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/spellcheck).

- `onFocus`: `(e: FocusEvent<HTMLInputElement>) => void`

  Handler that is called when the element receives focus.

- `onBlur`: `(e: FocusEvent<HTMLInputElement>) => void`

  Handler that is called when the element loses focus.

- `autoFocus`: `boolean`

  Whether the element should receive focus on render.

- `isRequired`: `boolean`

  Whether user input is required on the input before form submission.

- `isInvalid`: `boolean`

  Whether the input value is invalid.

- `isDisabled`: `boolean`

  Whether the input is disabled.

- `isReadOnly`: `boolean`

  Whether the input can be selected but not changed by the user.

- `value`: `string`

  The current value (controlled).

- `defaultValue`: `string`

  The default value (uncontrolled).

- `onChange`: `(value: string) => void`

  Handler that is called when the value changes.

- `onSubmit`: `(value: string) => void`

  Handler that is called when the SearchField is submitted.

- `onClear`: `() => void`

  Handler that is called when the clear button is pressed.

**Props: `StyleProps`**

- `margin`: `Responsive<Spacing | "auto">`

  The amount of margin applied to all edges of this component.

- `marginX`: `Responsive<Spacing | "auto">`

  The amount of margin applied to the left and right edges of this component. Takes priority over `margin`.

- `marginY`: `Responsive<Spacing | "auto">`

  The amount of margin applied to the top and bottom edges of this component. Takes priority over `margin`.

- `marginTop`: `Responsive<Spacing | "auto">`

  The amount of margin applied to the top edge of this component. Takes priority over `marginY` and `margin`.

- `marginRight`: `Responsive<Spacing | "auto">`

  The amount of margin applied to the right edge of this component. Takes priority over `marginX` and `margin`.

- `marginBottom`: `Responsive<Spacing | "auto">`

  The amount of margin applied to the bottom edge of this component. Takes priority over `marginY` and `margin`.

- `marginLeft`: `Responsive<Spacing | "auto">`

  The amount of margin applied to the left edge of this component. Takes priority over `marginX` and `margin`.
