> ## Documentation Index
> Fetch the complete documentation index at: https://anvil.servicetitan.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Toast - Web

> Toasts are temporary alerts that appear as a direct result of a user action.

> [!NOTE]
>
> For development, import `toast` from
> `@servicetitan/anvil2`. For design, find it in the
> [Anvil2 file](https://www.figma.com/design/xaNQsvRKczoxu7pj0M6QT8/Anvil2-v3).

![](https://mintcdn.com/servicetitan/H5FwKyiqhPVZ1UJQ/images/docs/web/components/shared/toast-main-image.png?fit=max\&auto=format\&n=H5FwKyiqhPVZ1UJQ\&q=85\&s=44599d3fe91f9599965341df10901932)

## Anatomy

The Toast consists of four primary elements that work together to create temporary alerts that appear as a direct result of a user action.

![Toast
anatomy](https://mintcdn.com/servicetitan/ar8TJanaRSxOpbCO/images/docs/web/components/toast/design/toast-anatomy.png?fit=max\&auto=format\&n=ar8TJanaRSxOpbCO\&q=85\&s=cb5a2fc28ff1cb161d64e58525909700)

1. Title
2. Body content
3. Actions
4. Close button

## Options

The Toast supports the following configurations to accommodate various notification scenarios.

### Status

![Toast status
examples](https://mintcdn.com/servicetitan/ar8TJanaRSxOpbCO/images/docs/web/components/toast/design/toast-status-examples.png?fit=max\&auto=format\&n=ar8TJanaRSxOpbCO\&q=85\&s=2aaf186846ba911401f3b03caaffb3d8)

| Type | Description |
| - | - |
| Informational | Non-essential information as the result of a user action. |
| Success | Confirmation that a task was successfully completed. |
| Warning | Information to warn users of a potential issue as the result of an action. Often paired with an action to help users recover. |
| Critical/Error | Used to communicate an error or other failure. Often paired with an action to help users recover. |

### Content Area

![Toast content area
examples](https://mintcdn.com/servicetitan/ar8TJanaRSxOpbCO/images/docs/web/components/toast/design/toast-content-area-examples.png?fit=max\&auto=format\&n=ar8TJanaRSxOpbCO\&q=85\&s=27fcc5505cec008a469952f95519f8db)

At minimum, a Toast consists of a title. Toasts also support body content, including a body message, actions, or progress bar.

### AI Mark

[ai-mark-toast](https://stackblitz.com/github/servicetitan/anvil2-docs-live-code/tree/main/examples/ai-mark-toast?embed=1\&hideNavigation=1\&hideExplorer=1\&terminalHeight=0\&file=src/App.tsx)

Include an [AI Mark](https://anvil.servicetitan.com/docs/components/ai-mark/code) in a Toast when the title should indicate AI-generated content.

## Usage Guidelines

| Standard | Requirement |
| - | - |
| DoNo interruption needed | The user does not need to be interrupted. |
| DoInforming with optional action | The user is being informed of an event, with the option to take action. |
| DoDelayed action results | The results of an action are delayed. |
| DoAppear anywhere in the application | The notification could appear anywhere in the application. |

See the [notification pattern](https://anvil.servicetitan.com/docs/patterns/notifications/web.md) for additional guidance.

#### Status Variations

##### Informational

Communicates operational information to the user. These are commonly used to denote the start of an operation, and usually includes follow-up notifications.

![Toast Status Info
Example](https://mintlify.s3.us-west-1.amazonaws.com/servicetitan/images/docs/web/components/toast/web/toast-status-info-example.png)

##### Success

Communicates the success of an operation, e.g., user preferences were updated.

Avoid including the term "successfully" in success Toasts as it duplicates information.

![Toast Status Success
Example](https://mintlify.s3.us-west-1.amazonaws.com/servicetitan/images/docs/web/components/toast/web/toast-status-success-example.png)

##### Critical/Error

Critical Toasts are used when an operation was unable to be performed or has failed. Page-specific and form errors should utilize the Alert notification. When applicable, users should be able to take action on an operation.

![Toast Status Error
Example](https://mintlify.s3.us-west-1.amazonaws.com/servicetitan/images/docs/web/components/toast/web/toast-status-error-example.png)

##### Warning

Warnings are distinct from errors and represent issues that do not need an immediate resolution, but still need to be addressed. Unintended consequences in an operation and fallback choices are common examples. In general, users should be able to take action on a warning.

![Toast Status Warning
Example](https://mintlify.s3.us-west-1.amazonaws.com/servicetitan/images/docs/web/components/toast/web/toast-status-warning-example.png)

### Alternatives

#### Toast vs Alert

Alerts are used to communicate information about either part of a page or a whole page. Alerts can be used to summarize information, such as a summary of errors.

Toasts are brief pieces of information and usually appear as the result of user action.

#### Toast vs Announcement

Announcements are used to convey app-wide messages, such as a new release being available, application maintenance, or sandbox information.

Toasts are short pieces of information usually prompted by user action.

## Behavior

The Toast responds to timing requirements and positioning constraints while maintaining consistent notification appearance.

### How to Use

#### Positioning

Toasts are positioned in the top-right of the screen on top of application UI. Toasts do not cover any part of the global navigation.

#### Timing

By default, Toasts are persistent until dismissed by a user. An optional timeout is available. The recommended duration is 8 seconds, but this can be customized.

Toasts are always persistent in the following cases:

* When there are any actions within the Toast.
* When a Toast contains a Progress Bar.
* When a Toast is in an error state.

Avoid adding a timeout when a Toast contains information that users may need to copy or remember.

#### Progress Bar

When the time to complete a task can be calculated, pair a Toast with a [Progress Bar](https://anvil.servicetitan.com/docs/components/progress-bar/design).

## Content

Content within the Toast should be brief, scannable, and actionable.

### Titles should be brief and scannable and as specific as possible.

Use sentence case. Don't use periods and exclamation points, and avoid articles: a, an, the.

### Write titles as verbs

Titles should have a clear verb + noun question or statement.

![Toast "Do" example that has title that says "Unable to create geofence"
and body text that says "We weren't able to create the geofence. Please try
again."](https://mintcdn.com/servicetitan/ar8TJanaRSxOpbCO/images/docs/web/components/toast/design/toast-do-example-that-has-title-that-says-unable-to-create-geofence-and-body-text-that-says-we-werent-able-to-create-the-geofence-please-try-again.png?fit=max\&auto=format\&n=ar8TJanaRSxOpbCO\&q=85\&s=13412db9543f8261f15b4672621b8919)

> [!TIP]
>
> **Do**

![Toast "Don't" example that has a title that says "Request failed" and body
text that says "Something went wrong. Please try
again."](https://mintcdn.com/servicetitan/ar8TJanaRSxOpbCO/images/docs/web/components/toast/design/toast-dont-example-that-has-a-title-that-says-request-failed-and-body-text-that-says-something-went-wrong-please-try-again.png?fit=max\&auto=format\&n=ar8TJanaRSxOpbCO\&q=85\&s=286cbb50bde39c463982f1f73ee81049)

> [!CAUTION]
>
> **Don't**

### Messages that can be communicated in a single header don't require body text.

Body text should only provide information that is not included in the header. Do not repeat information that's already in the header.

![Toast "Do" example with only a title that says "Geofence created
successfully"](https://mintcdn.com/servicetitan/ar8TJanaRSxOpbCO/images/docs/web/components/toast/design/toast-do-example-with-only-a-title-that-says-geofence-created-successfully.png?fit=max\&auto=format\&n=ar8TJanaRSxOpbCO\&q=85\&s=3ec92b9f5f31ae2021f3020eb90eed94)

> [!TIP]
>
> **Do**

![Toast "Don't" example with a title that says "Geofence created
successfully" and body text that says "The geofence has been created
successfully"](https://mintcdn.com/servicetitan/ar8TJanaRSxOpbCO/images/docs/web/components/toast/design/toast-dont-example-with-a-title-that-says-geofence-created-successfully-and-body-text-that-says-the-geofence-has-been-created-successfully.png?fit=max\&auto=format\&n=ar8TJanaRSxOpbCO\&q=85\&s=c4617e564981e203c3119858eeffb702)

> [!CAUTION]
>
> **Don't**

### Make body content concise, informative, and actionable

Use imperative verbs when telling users what they need to know or do. Avoid permissive language like "you can".

Whenever possible, include an in-line action for a user to take so that they can readily address the issue explained in the message.

![Toast "Do" example with title that says "Some drivers haven't been mapped"
and body text that says "All drivers must be mapped to a technician before
you can move to the next
step."](https://mintcdn.com/servicetitan/ar8TJanaRSxOpbCO/images/docs/web/components/toast/design/toast-do-example-with-title-that-says-some-drivers-havent-been-mapped-and-body-text-that-says-all-drivers-must-be-mapped-to-a-technician-before-you-can-move-to-the-next-step.png?fit=max\&auto=format\&n=ar8TJanaRSxOpbCO\&q=85\&s=3ce33f1499f549e986cb6897c8ef1989)

> [!TIP]
>
> **Do**

![Toast "Don't" example that has a title that says "Request failed" and body
text that says "Something went wrong. Please try creating
again."](https://mintcdn.com/servicetitan/ar8TJanaRSxOpbCO/images/docs/web/components/toast/design/toast-dont-example-that-has-a-title-that-says-request-failed-and-body-text-that-says-something-went-wrong-please-try-creating-again.png?fit=max\&auto=format\&n=ar8TJanaRSxOpbCO\&q=85\&s=e231bef4acb36b3e587c4957b1f40025)

> [!CAUTION]
>
> **Don't**

### Buttons should be clear, predictable, and action-oriented

Users should be able to predict what will happen when they click a button.

Lead with a strong verb that encourages action. Use a verb/noun pair on actions in most cases. Common actions like Save, Close, or Cancel do not require an accompanying noun.

![Toast "Do" example that has title that says "Submission error" and body
text that says "An issue was encountered process the request. Please try
again or view the results for more details." and two buttons. The first
button says "Try Again" and the second button says "View
Results"](https://mintcdn.com/servicetitan/ar8TJanaRSxOpbCO/images/docs/web/components/toast/design/toast-do-example-that-has-title-that-says-submission-error-and-body-text-that-says-an-issue-was-encountered-process-the-request-please-try-again-or-view-the-results-for-more-details-and-two-buttons-th.png?fit=max\&auto=format\&n=ar8TJanaRSxOpbCO\&q=85\&s=2fd3b99665c93842891a1ca65a19e569)

> [!TIP]
>
> **Do**

![Toast "Don't" example with a title that says "Submission error" with no
body text and two buttons. The first button says "Results" and the second
button says
"View"](https://mintcdn.com/servicetitan/ar8TJanaRSxOpbCO/images/docs/web/components/toast/design/toast-dont-example-with-a-title-that-says-submission-error-with-no-body-text-and-two-buttons-the-first-button-says-results-and-the-second-button-says-view.png?fit=max\&auto=format\&n=ar8TJanaRSxOpbCO\&q=85\&s=73e5d60bfe0f3ece0d686103defda20b)

> [!CAUTION]
>
> **Don't**

## Code

**Implementation**

[toast-playground](https://stackblitz.com/github/servicetitan/anvil2-docs-live-code/tree/main/examples/toast-playground?embed=1\&hideNavigation=1\&hideExplorer=1\&terminalHeight=0\&file=src/App.tsx)

## Common Examples

### Toast methods

There are seven `toast` methods available in Anvil2. Four of them are used to create standard toasts with varying styles:

* `toast.info()`
* `toast.success()`
* `toast.warning()`
* `toast.danger()`

The fifth, `toast.promise()`, generates a pending toast, and uses a completed promise to update the toast based on a response.

The other two are used to manage existing toast messages:

* `toast.update()`
* `toast.dismiss()`

```tsx theme={null}
import { Button, toast } from "@servicetitan/anvil2";

function ExampleComponent() {
  return (
    <Button
      onClick={() =>
        toast.info({
          title: "Toast title",
          message: "Lorem ipsum dolor sit amet",
        })
      }
    >
      Click me!
    </Button>
  );
}
```

### Toasters

To use the `toast` methods, there must be a `Toaster` component rendered somewhere up the tree, usually at the root of the application. The toaster is the container that toast messages appear in, and manages positioning, stacking, and dismiss timing updates.

```tsx theme={null}
import { AnvilProvider, Toaster } from "@servicetitan/anvil2";

function App({ children }) {
  return (
    <>
      <Toaster id="app-toaster" />
      <AnvilProvider>
        {children}
      </AnvilProvider>
    </>
  )
}
```

#### Multiple toasters

In order to avoid double-rendering toast messages, the `Toaster` component will only render toast messages if it doesn't detect another `Toaster`. This means if you are using a `Toaster` in a standalone MFE, it will display toasts, but will defer to the host's `Toaster` when it is loaded in the host application.

**Note:** A limitation exists where the `Toaster` cannot detect a `Toaster` in a sibling MFE. For this reason, there must be a `Toaster` in the host app to which MFEs will defer.

#### Toaster config

To ensure consistency, the `Toaster` component should handle most of the config options for toast messages within an app. The following props can be added:

```tsx theme={null}
type ToasterProps = {
  // defaults
  id: string;
  focusKey?: string; // "t"
  toastsBeforeStack?: number; // 3
};
```

### Showing basic toasts

#### Basic toast method examples

[toast-method](https://stackblitz.com/github/servicetitan/anvil2-docs-live-code/tree/main/examples/toast-method?embed=1\&hideNavigation=1\&hideExplorer=1\&terminalHeight=0\&file=src/App.tsx)

#### Toast method config object

All of the basic toast methods accept a config object with the following shape:

```tsx theme={null}
type toastProps = {
  title: string;
  actions?: { primary: ToastAction; secondary?: ToastAction };
  aiMark?: boolean | AiMarkWithTooltipOrPopoverConfig;
  containerClassName?: string;
  duration?: number | false;
  message?: string;
  onClose?: MouseEventHandler<HTMLButtonElement>;
  onDismiss?: () => void;
  progress?: number | "indeterminate";
  toastClassName?: string;
}
```

#### Notes for basic toast methods

* Toasts with `actions` will ignore the duration setting to allow users a chance to perform an action.
* The toast config passed to a toast method will override some of the defaults set on the `Toaster` component.

### Using promise toasts

#### Promise toast example

[toast-promise](https://stackblitz.com/github/servicetitan/anvil2-docs-live-code/tree/main/examples/toast-promise?embed=1\&hideNavigation=1\&hideExplorer=1\&terminalHeight=0\&file=src/App.tsx)

#### Promise toast method config object

The config object passed to toast.promise() should have three properties – `loading`, `success`, and `error`.

```tsx theme={null}
type PromiseToastMethodConfig = {
  loading: toastProps; // same as basic config object
  success: (message: string) => toastProps;
  error: (message: string) => toastProps;
};
```

#### Notes for promise toasts

* The first parameter of the `toast.promise()` method should be a `Promise` that either resolves or rejects. Otherwise, the loading state will render indefinitely.

### Using progress toasts

[toast-progress](https://stackblitz.com/github/servicetitan/anvil2-docs-live-code/tree/main/examples/toast-progress?embed=1\&hideNavigation=1\&hideExplorer=1\&terminalHeight=0\&file=src/App.tsx)

The `progress` property can be passed to any toast creation method or `toast.update()` to display a [Progress Bar](https://anvil.servicetitan.com/docs/components/progress-bar/design) inside the toast.

#### Notes for progress toasts

* Set `progress` to a number from 0–100 for a determinate progress bar, or `"indeterminate"` for an indeterminate one.
* Use `toast.update()` to advance the progress value as work completes.
* Set `duration: false` to prevent the toast from auto-dismissing before the operation finishes.
* When the operation completes, use `toast.update()` with a new `status` to change the toast's visual style.

### Updating toasts

[toast-update](https://stackblitz.com/github/servicetitan/anvil2-docs-live-code/tree/main/examples/toast-update?embed=1\&hideNavigation=1\&hideExplorer=1\&terminalHeight=0\&file=src/App.tsx)

#### Notes for updating toasts

* An `id` for the toast message to be updated is required as the first parameter of the `toast.update()` method. This `id` is provided as the return value of any of the toast creation methods.
* Any of the `toastProps` can be updated using this method, including `progress`.
* `status` can also be set in `toast.update()` to change the toast's visual style (e.g. changing from `"info"` to `"success"` when an operation completes).

### Dismissing toasts

[toast-dismiss](https://stackblitz.com/github/servicetitan/anvil2-docs-live-code/tree/main/examples/toast-dismiss?embed=1\&hideNavigation=1\&hideExplorer=1\&terminalHeight=0\&file=src/App.tsx)

#### When toasts are dismissed

> [!NOTE]
>
> **Toasts without `actions`** auto-dismiss after the `duration` expires.
>
> **Toasts with `actions`** ignore the `duration` setting and are only dismissed when the user takes direct action: pressing the "x" button, clicking a toast action button, or calling `toast.dismiss()` programmatically.

Toasts can be dismissed in four ways:

1. By pressing the "x" button on the toast message.
2. By swiping the toast message off the screen on touch screens.
3. Automatically after the `duration` expires, if supplied on the `Toaster` or in the `toast` method.
4. Programmatically using the `toast.dismiss()` method.

#### Notes for dismissing toasts

* The `toast.dismiss()` method accepts an optional `id` parameter to dismiss a specific toast message. This `id` is given as the return value of any of the toast creation methods.
* If no `id` is provided, all visible toast messages will be dismissed.
* If a `duration` is provided, and the toast becomes stacked (hidden), the timeout is paused and restarted once the toast becomes visible again.

#### Callbacks for toast dismissal

There are two callback parameters available on the toast methods:

* `onClose` is passed to the "x" button's `onClick`, so it is only run when the user activates the button
* `onDismiss` is run anytime the toast is removed, including on "x" button click, when `toast.dismiss()` is run, or when the `duration` expires on the toast

### Using toast actions

[toast-actions](https://stackblitz.com/github/servicetitan/anvil2-docs-live-code/tree/main/examples/toast-actions?embed=1\&hideNavigation=1\&hideExplorer=1\&terminalHeight=0\&file=src/App.tsx)

The `actions` property of the `toastConfig` that is passed to `toast` creation methods can be used to add one or two [Button](https://anvil.servicetitan.com/docs/components/button/design) components to the toast message. The `actions` property accepts an object with two properties:

```tsx theme={null}
type ActionsParameter = { primary: ToastAction; secondary?: ToastAction };
```

The `ToastAction` type is used to update some [Button](https://anvil.servicetitan.com/docs/components/button/design) props of the action button.

```tsx theme={null}
type ToastAction = Pick<ButtonProps, "appearance" | "onClick"> & {
  label: string;
};
```

### AI Mark

Add an [AI Mark](https://anvil.servicetitan.com/docs/components/ai-mark/code) inline after the toast title by including `aiMark` in the toast config. Use `true` for the sparkle only, or pass tooltip or popover configuration.

[ai-mark-toast](https://stackblitz.com/github/servicetitan/anvil2-docs-live-code/tree/main/examples/ai-mark-toast?embed=1\&hideNavigation=1\&hideExplorer=1\&terminalHeight=0\&file=src/App.tsx)

### Toast event handling

Whenever a toast is added, updated, or dismissed, the `Toaster` component runs the `onToastEvent` callback with the following object passed in the event:

```tsx theme={null}
type ToastEventType = {
  eventType: "add" | "update" | "dismiss" | "dismiss-all";
  toastCount: number;
  id?: string;
  toasterId?: string;
  toastProps?: ToastProps | ToastUpdateProps;
};
```

Some of the parameters will only show when certain toast methods are called. For example, `toast.dismiss()` will not include `toastProps`, since it affects all of the existing toasts.

#### MFE Toaster note for toast event handling

The `Toaster` used in the monolith/host app will take precedence over any loaded by an MFE, so the `onToastEvent` will generally not work for MFEs that are run in a host app that includes its own `Toaster`, such as monolith.

## React Accessibility

* When `actions` are used, do not add a `duration` so that users have time to decide if they would like to take action.
* By default, pressing the "t" key on the keyboard while a toast message is visible will shift focus to the toast. This is announced by screen readers to make the messages easily accessible for some users. If the "t" key is used for another hot key, this can be overridden using the `focusKey` prop of the `Toaster`.

For further guidance on creating accessible status updates, see [accessible status messages and notifications best practices](https://anvil.servicetitan.com/docs/accessibility/changing-content.md#status-updates).

**Toaster Props**

```tsx theme={null}
<Toaster
  id="app-toaster"
  focusKey="t"
  toastsBeforeStack={3}
  onToastEvent={(event) => console.log(event)}
/>
```

## `Toaster` Props

MFE Warning: When a `Toaster` is used in an MFE that is loaded into monolith, or any other host app that includes its own `Toaster`, the host app `Toaster` will take precedence. Any props used on an MFE `Toaster` will only work when it is used outside of the host app. This allows for a centralized config and rendering in the host application.

**id** `string` *required*

**focusKey** `string` (default: t)

Hot key for focusing on first toast message.

**onToastEvent** `(toastEvent: ToastEventType) =\> void`

See [Toast event
handling](https://anvil.servicetitan.com/docs/components/toast/code#toast-event-handling)

**toastsBeforeStack** `number` (default: 3)

Determines how many toasts to show before they stack in the UI.

**Toast Methods**

```tsx theme={null}
// Basic toast methods
toast.info({ title: "Info", message: "Message" });
toast.success({ title: "Success", message: "Message" });
toast.warning({ title: "Warning", message: "Message" });
toast.danger({ title: "Danger", message: "Message" });

// Promise toast
toast.promise(promise, {
  loading: { title: "Loading..." },
  success: (message) => ({ title: "Success", message }),
  error: (message) => ({ title: "Error", message }),
});

// Update toast
toast.update(id, { title: "Updated", message: "New message" });

// Dismiss toast
toast.dismiss(id);
```

## Toast Methods

### Basic toast creation methods API

This API applies to the following methods:

* `toast.info()`
* `toast.success()`
* `toast.warning()`
* `toast.danger()`

**config** `toastProps`

See [Toast method config
object](https://anvil.servicetitan.com/docs/components/toast/code#toast-method-config-object).

This API applies to the `toast.promise()` method:

**promise** `Promise`

See [Notes for promise
toasts](https://anvil.servicetitan.com/docs/components/toast/code#notes-for-promise-toasts).

**config** `\{ loading: toastProps, success: (message: string) =\> toastProps, error: (message: string) =\> toastProps\}`

See [Promise toast method config
object](https://anvil.servicetitan.com/docs/components/toast/code#promise-toast-method-config-object).

### Updating toasts API

This API applies to the `toast.update()` method:

**id** `string`

See [Updating toasts](https://anvil.servicetitan.com/docs/components/toast/code#updating-toasts).

**updatedConfig** `Partial\<toastProps\> & \{ status?: "info" | "success" | "warning" | "danger" \}`

Only add properties that should change. Use `status` to change the toast's visual style on update.

### Dismissing toasts API

This API applies to the `toast.dismiss()` method:

**id** `string`

If omitted, all toasts are dismissed. See [Updating
toasts](https://anvil.servicetitan.com/docs/components/toast/code#dismissing-toasts).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.