# Input Text

Input text is used in forms that accept short or long answers from users.

## Design & usage guidelines

### Controlled

Use this to allow users to provide short answers.

```tsx
import React, { useState } from "react";
import type { InputTextProps } from "@jobber/components/InputText";
import { InputText } from "@jobber/components/InputText";

export const InputTextBasicExample = ({
  onChange,
  ...props
}: Partial<InputTextProps>) => {
  const [value, setValue] = useState(props.value ?? "");

  return (
    <InputText
      name="age"
      placeholder="Age in words"
      {...props}
      value={value}
      onChange={newValue => {
        setValue(newValue);
        onChange?.(newValue);
      }}
    />
  );
};
```

**Show code**

### Multiline

Use this to allow users to provide long answers. The default number of rows is
three. Note that `loading={true}` is unimplemented for multiline input text.

For web, you can set a minimum and maximum number of rows. See:
[Web/rows example](/storybook/web/?path=/story/components-forms-and-inputs-inputtext--multiline).

```tsx
import React, { useState } from "react";
import type { InputTextProps } from "@jobber/components/InputText";
import { InputText } from "@jobber/components/InputText";

export function InputTextMultilineExample(
  props: Partial<Omit<InputTextProps, "multiline">>,
) {
  const [value, setValue] = useState<string>(props.value ?? "");

  return (
    <InputText
      multiline={true}
      placeholder="Describe your age"
      {...props}
      value={value}
      onChange={(
        newValue: string,
        event?: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
      ) => {
        setValue(newValue);
        props.onChange?.(newValue, event);
      }}
    />
  );
}
```

### Prefix/suffix

Use a prefix or suffix when additional visual cues about an input's function may
be helpful.

Some fields have common visual patterns such as "search" having a magnifying
glass icon, "Select" having a downwards arrow, or currency inputs having a
currency symbol. These signifiers reinforce the purpose of the input to increase
[Recognition over Recall](https://www.nngroup.com/articles/ten-usability-heuristics/)
and align the input with
[Consistency and Standards](https://www.nngroup.com/articles/ten-usability-heuristics/).
With clearer guidance around the purpose of inputs, the user is able to better
focus on the task at hand.

Either affix can be given an `onClick` to make it an action, which renders the
affix icon as a button. An actioned affix requires both an `icon` and an
`ariaLabel` to name the button — affix labels are not actionable.

```tsx
import React, { useState } from "react";
import type { InputTextProps } from "@jobber/components/InputText";
import { InputText } from "@jobber/components/InputText";
import { Content } from "@jobber/components/Content";

export function InputTextPrefixSuffixExample(
  props: Partial<Omit<InputTextProps, "multiline" | "rows">>,
) {
  const [invoiceTotal, setInvoiceTotal] = useState<string>(
    props.value ?? "1,000,000",
  );
  const [search, setSearch] = useState<string>(props.value ?? "");

  const handleChange = (
    newValue: string,
    event?: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
  ) => {
    setInvoiceTotal(newValue);
    props.onChange?.(newValue, event);
  };

  const handleSearchChange = (
    newValue: string,
    event?: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
  ) => {
    setSearch(newValue);
    props.onChange?.(newValue, event);
  };

  return (
    <Content>
      <InputText
        placeholder="Invoice Total"
        value={invoiceTotal}
        onChange={handleChange}
        prefix={{ label: "$", icon: "invoice" }}
        suffix={{ label: ".00" }}
        {...props}
      />
      <InputText
        placeholder="Search"
        prefix={{
          icon: "search",
          ariaLabel: "submit search",
          onClick: () => alert("This could submit a search"),
        }}
        value={search}
        onChange={handleSearchChange}
        suffix={{
          icon: "cross",
          ariaLabel: "clear search",
          onClick: () => alert("This could clear a search value"),
        }}
        {...props}
      />
    </Content>
  );
}
```

### Validation message

You can add your own custom validation messages on a field to assist the user in
successfully completing a form. This doesn't *replace* server-side validation,
but minimizes the need for it as the user should be set up for success by proper
guidance pre-submission before any "bad" data gets to the server.

Follow the
[product vocabulary](../product-vocabulary/product-vocabulary.md#component-view-general-phrasing)
for guidance on writing helpful error messages.

```tsx
import React, { useState } from "react";
import type { InputTextProps } from "@jobber/components/InputText";
import { InputText } from "@jobber/components/InputText";

export function InputTextValidationExample(
  props: Partial<Omit<InputTextProps, "multiline" | "rows">>,
) {
  const [value, setValue] = useState("");
  const [error, setError] = useState<string | undefined>();

  function handleChange(newValue: string) {
    setValue(newValue);

    if (!newValue) {
      setError("You have to tell us your age");
    } else if (!isNaN(Number(newValue))) {
      setError("Type your age in words please.");
    } else if (newValue.length >= 10) {
      setError("That seems too old.");
    } else {
      setError(undefined);
    }
  }

  return (
    <InputText
      placeholder="What's your age"
      value={value}
      onChange={handleChange}
      invalid={!!error}
      error={error}
      {...props}
    />
  );
}
```

## States

### Disabled

```tsx
import React from "react";
import type { InputTextProps } from "@jobber/components/InputText";
import { InputText } from "@jobber/components/InputText";

export function InputTextDisabledExample(
  props: Partial<Omit<InputTextProps, "multiline" | "rows">>,
) {
  return (
    <InputText
      placeholder="Credit card"
      value="**** **** **** 1234"
      disabled={true}
      {...props}
    />
  );
}
```

### Invalid

For mobile, you can pass a string to the `invalid` prop to display an error.
See:
[Mobile/invalid example](/storybook/mobile/?path=/story/components-forms-and-inputs-inputtext--invalid).

```tsx
import React from "react";
import { InputText } from "@jobber/components/InputText";
import type { InputTextProps } from "@jobber/components/InputText";

export function InputTextInvalidExample(
  props: Partial<Omit<InputTextProps, "multiline" | "rows">>,
) {
  return (
    <InputText placeholder="Email" value="atlantis" invalid={true} {...props} />
  );
}
```

### External label

You can use `FormFieldLabel` to provide a label outside of the input. The
`showMiniLabel` prop on `InputText` can be used to hide the mini label that
appears when a value is provided.

```tsx
import React, { useState } from "react";
import type { InputTextProps } from "@jobber/components/InputText";
import { InputText } from "@jobber/components/InputText";
import { FormFieldLabel } from "@jobber/components/FormField";

export function InputTextExternalLabelExample(
  props: Partial<Omit<InputTextProps, "multiline" | "rows">>,
) {
  const [value, setValue] = useState<string>(props.value ?? "");

  return (
    <div style={{ width: "100%" }}>
      <FormFieldLabel external={true} htmlFor="ext-input">
        External label
      </FormFieldLabel>
      <InputText
        id="ext-input"
        name="name"
        clearable="always"
        showMiniLabel={false}
        {...props}
        value={value}
        onChange={(
          newValue: string,
          event?: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
        ) => {
          setValue(newValue);
          props.onChange?.(newValue, event);
        }}
      />
    </div>
  );
}
```

### Keyboard

Determine what default keyboard appears on mobile.

```tsx
import React, { useState } from "react";
import type { InputTextProps } from "@jobber/components/InputText";
import { InputText } from "@jobber/components/InputText";

export function InputTextKeyboardExample(
  props: Partial<Omit<InputTextProps, "multiline" | "rows">>,
) {
  const [value, setValue] = useState<string>(props.value ?? "");

  return (
    <InputText
      placeholder="Describe your age"
      inputMode="numeric"
      {...props}
      value={value}
      onChange={(
        newValue: string,
        event?: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
      ) => {
        setValue(newValue);
        props.onChange?.(newValue, event);
      }}
    />
  );
}
```


## Props

### Mobile

| Prop | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `accessibilityHint` | `string` | No | — | An accessibility hint helps users understand what will happen when they perform an action on the accessibility elemen... |
| `accessibilityLabel` | `string` | No | — | VoiceOver will read this string when a user selects the associated element |
| `assistiveText` | `string` | No | — | Text that helps the user understand the input |
| `autoCapitalize` | `"characters" | "none" | "sentences" | "words"` | No | — | Determines where to autocapitalize |
| `autoComplete` | `"email" | "name" | "additional-name" | "address-line1" | "address-line2" | "birthdate-day" | "birthdate-full" | "birthdate-month" | "birthdate-year" | "cc-csc" | "cc-exp" | ... 45 more ... | "off"` | No | — | Determines which content to suggest on auto complete, e.g.`username`. Default is `off` which disables auto complete  ... |
| `autoCorrect` | `boolean` | No | — | Turn off autocorrect |
| `autoFocus` | `boolean` | No | — | Automatically focus the input after it is rendered |
| `clearable` | `Clearable` | No | — | Add a clear action on the input that clears the value.  You should always use `while-editing` if you want the input t... |
| `defaultValue` | `string` | No | — | Default value for when component is uncontrolled |
| `disabled` | `boolean` | No | — | Disable the input |
| `invalid` | `boolean | string` | No | — | Highlights the field red and shows message below (if string) to indicate an error |
| `keyboard` | `"decimal-pad" | "default" | "email-address" | "numbers-and-punctuation" | "numeric" | "phone-pad"` | No | — | Determines what keyboard is shown |
| `loading` | `boolean` | No | — | Show loading indicator. |
| `loadingType` | `"glimmer" | "spinner"` | No | — | Change the type of loading indicator to spinner or glimmer. |
| `multiline` | `boolean` | No | — | Determines if inputText will span multiple lines. Default is `false`  https://reactnative.dev/docs/textinput#multiline |
| `name` | `string` | No | — | Name of the input. |
| `onBlur` | `(event?: FocusEvent) => void` | No | — | Callback that is called when the text input is blurred |
| `onChangeText` | `(newValue: string) => void` | No | — | Simplified callback that only provides the new value @param newValue |
| `onFocus` | `(event?: FocusEvent) => void` | No | — | Callback that is called when the text input is focused @param event |
| `onSubmitEditing` | `(event?: SyntheticEvent<Element, Event>) => void` | No | — | Callback that is called when the text input's submit button is pressed @param event |
| `placeholder` | `string` | No | — | Hint text that goes above the value once the field is filled out |
| `prefix` | `{ icon?: IconNames; label?: string; }` | No | — | Symbol to display before the text input |
| `readonly` | `boolean` | No | — | Makes the input read-only |
| `ref` | `Ref<InputTextRef>` | No | — | Allows getting a ref to the component instance. Once the component unmounts, React will set `ref.current` to `null` (... |
| `secureTextEntry` | `boolean` | No | — | Use secure text entry |
| `showMiniLabel` | `boolean` | No | `true` | Controls the visibility of the mini label that appears inside the input when a value is entered. By default, the plac... |
| `spellCheck` | `boolean` | No | — | Determines whether spell check is used. Turn it off to hide empty autoCorrect suggestions when autoCorrect is off.  *... |
| `styleOverride` | `InputTextStyleOverride` | No | — | Custom styling to override default style of the input text |
| `suffix` | `{ icon?: IconNames; label?: string; onPress?: () => void; }` | No | — | Symbol to display after the text input |
| `testID` | `string` | No | — | Used to locate this view in end-to-end tests |
| `textContentType` | `"none" | "name" | "nickname" | "password" | "username" | "URL" | "addressCity" | "addressCityAndState" | "addressState" | "countryName" | "creditCardNumber" | "creditCardExpiration" | ... 33 more ... | "shipmentTrackingNumber"` | No | — | Determines which content to suggest on auto complete, e.g.`username`. Default is `none` which disables auto complete ... |
| `toolbar` | `ReactNode` | No | — | Add a toolbar below the input field for actions like rewriting the text. |
| `toolbarVisibility` | `"always" | "while-editing"` | No | — | Change the behaviour of when the toolbar becomes visible. |
| `transform` | `{ input?: (v: any) => string; output?: (v: string) => any; }` | No | — | transform object is used to transform the internal TextInput value It's useful for components like InputNumber where ... |
| `validations` | `RegisterOptions` | No | — | Shows an error message below the field and highlight the field red when value is invalid |
| `value` | `string` | No | — | Set the component to a given value |
