> Native Solid 2 fork. Original documentation and designs © WorkOS; historical posts retain their original context.

# Toast

A succinct message that is displayed temporarily.

## Features

- Automatically closes.

- Pauses closing on hover, focus and window blur.

- Supports hotkey to jump to toast viewport.

- Supports closing via swipe gesture.

- Exposes CSS variables for swipe gesture animations.

- Can be controlled or uncontrolled.

## Anatomy

Import the component.

```jsx
import { Toast } from "@radix-solid/primitives";

export default () => <Toast.Provider>

		<Toast.Root>

			<Toast.Title />

			<Toast.Description />

			<Toast.Action altText="Open the notification">Open</Toast.Action>

			<Toast.Close />

		</Toast.Root>



		<Toast.Viewport />

	</Toast.Provider>;
```

## API Reference

### Provider

The provider that wraps your toasts and toast viewport. It usually wraps the application.

| Prop                                                                                                                                                                                      | Type      | Default          |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | ---------------- |
| `duration`The time in milliseconds that should elapse before automatically closing each toast.                                                                                            | `number`  | `5000`           |
| `label*`An author-localized label for each toast. Used to help screen reader users associate the interruption with a toast.                                                               | `string`  | `"Notification"` |
| `swipeDirection`The direction of the pointer swipe that should close the toast.                                                                                                           | `enum`    | `"right"`        |
| `swipeThreshold`The distance in pixels that the swipe gesture must travel before a close is triggered.                                                                                    | `number`  | `50`             |
| `announcerContainer`An optional container where the toast announcements should be appended. This is useful when working with focus traps or modal dialogs that make other elements inert. | `Element` | `document.body`  |

### Viewport

The fixed area where toasts appear. Users can jump to the viewport by pressing a hotkey. It is up to you to ensure the discoverability of the hotkey for keyboard users.

| Prop                                                                                                                                                                                                                                              | Type       | Default                      |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | ---------------------------- |
| `asChild`Render through a single-target factory, merging props and behavior with the chosen host. Read our [Composition](../guides/composition) guide for more details.                                                                           | `boolean`  | `false`                      |
| `hotkey`The keys to use as the keyboard shortcut that will move focus to the toast viewport. Use `event.code` value for each key from [keycode.info](https://keycode.info/). For meta keys, use `ctrlKey`, `shiftKey`, `altKey` and/or `metaKey`. | `string[]` | `["F8"]`                     |
| `label`An author-localized label for the toast region to provide context for screen reader users when navigating page landmarks. The available \`{hotkey}\` placeholder will be replaced for you.                                                 | `string`   | `"Notifications ({hotkey})"` |

### Root

The toast that automatically closes. It should not be held open to [acquire a user response](/primitives/docs/components/toast#action).

| Prop                                                                                                                                                                                                                                                          | Type       | Default        |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | -------------- |
| `asChild`Render through a single-target factory, merging props and behavior with the chosen host. Read our [Composition](../guides/composition) guide for more details.                                                                                       | `boolean`  | `false`        |
| `type`Control the [sensitivity](/primitives/docs/components/toast#sensitivity) of the toast for accessibility purposes. For toasts that are the result of a user action, choose `foreground`. Toasts generated from background tasks should use `background`. | `enum`     | `"foreground"` |
| `duration`The time in milliseconds that should elapse before automatically closing the toast. This will override the value supplied to the provider.                                                                                                          | `number`   | —              |
| `defaultOpen`The open state of the dialog when it is initially rendered. Use when you do not need to control its open state.                                                                                                                                  | `boolean`  | `true`         |
| `open`The controlled open state of the dialog. Must be used in conjunction with `onOpenChange`.                                                                                                                                                               | `boolean`  | —              |
| `onOpenChange`Event handler called when the open state of the dialog changes.                                                                                                                                                                                 | `function` | —              |
| `onEscapeKeyDown`Event handler called when the escape key is down. It can be prevented by calling `event.preventDefault`.                                                                                                                                     | `function` | —              |
| `onPause`Event handler called when the dismiss timer is paused. This occurs when the pointer is moved over the viewport, the viewport is focused or when the window is blurred.                                                                               | `function` | —              |
| `onResume`Event handler called when the dismiss timer is resumed. This occurs when the pointer is moved away from the viewport, the viewport is blurred or when the window is focused.                                                                        | `function` | —              |
| `onSwipeStart`Event handler called when starting a swipe interaction. It can be prevented by calling `event.preventDefault`.                                                                                                                                  | `function` | —              |
| `onSwipeMove`Event handler called during a swipe interaction. It can be prevented by calling `event.preventDefault`.                                                                                                                                          | `function` | —              |
| `onSwipeEnd`Event handler called at the end of a swipe interaction. It can be prevented by calling `event.preventDefault`.                                                                                                                                    | `function` | —              |
| `onSwipeCancel`Event handler called when a swipe interaction is cancelled. It can be prevented by calling `event.preventDefault`.                                                                                                                             | `function` | —              |
| `forceMount`Used to force mounting when more control is needed. Useful when controlling animation with Solid-compatible animation libraries.                                                                                                                  | `boolean`  | —              |

| Data attribute           | Values                                   |
| ------------------------ | ---------------------------------------- |
| `[data-state]`           | `"open" \| "closed"`                     |
| `[data-swipe]`           | `"start" \| "move" \| "cancel" \| "end"` |
| `[data-swipe-direction]` | `"up" \| "down" \| "left" \| "right"`    |

| CSS Variable                 | Description                                                     |
| ---------------------------- | --------------------------------------------------------------- |
| `--radix-toast-swipe-move-x` | The offset position of the toast when horizontally swiping      |
| `--radix-toast-swipe-move-y` | The offset position of the toast when vertically swiping        |
| `--radix-toast-swipe-end-x`  | The offset end position of the toast after horizontally swiping |
| `--radix-toast-swipe-end-y`  | The offset end position of the toast after vertically swiping   |

### Title

An optional title for the toast.

| Prop                                                                                                                                                                    | Type      | Default |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | ------- |
| `asChild`Render through a single-target factory, merging props and behavior with the chosen host. Read our [Composition](../guides/composition) guide for more details. | `boolean` | `false` |

### Description

The toast message.

| Prop                                                                                                                                                                    | Type      | Default |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | ------- |
| `asChild`Render through a single-target factory, merging props and behavior with the chosen host. Read our [Composition](../guides/composition) guide for more details. | `boolean` | `false` |

### Action

An action that is safe to ignore to ensure users are not expected to complete tasks with unexpected side effects as a result of a [time limit](https://www.w3.org/TR/UNDERSTANDING-WCAG20/time-limits-required-behaviors.html).

When obtaining a user response is necessary, portal an [`AlertDialog`](/primitives/docs/components/alert-dialog) styled as a toast into the viewport instead.

| Prop                                                                                                                                                                    | Type      | Default |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | ------- |
| `asChild`Render through a single-target factory, merging props and behavior with the chosen host. Read our [Composition](../guides/composition) guide for more details. | `boolean` | `false` |
| `altText*`Describe an [alternative way to achieve the action](./toast#alternative-action) for screen reader users who cannot access the toast easily.                   | `string`  | —       |

### Close

A button that allows users to dismiss the toast before its duration has elapsed.

| Prop                                                                                                                                                                    | Type      | Default |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | ------- |
| `asChild`Render through a single-target factory, merging props and behavior with the chosen host. Read our [Composition](../guides/composition) guide for more details. | `boolean` | `false` |

## Examples

### Custom hotkey

Override the default hotkey using the `event.code` value for each key from [keycode.info](https://keycode.info/).

```jsx
<Toast.Provider>

	{/* ... */}

	<Toast.Viewport hotkey={["altKey", "KeyT"]} />

</Toast.Provider>
```

### Custom duration

Customise the duration of a toast to override the provider value.

```jsx
<Toast.Root duration={3000}>

	<Toast.Description>Saved!</Toast.Description>

</Toast.Root>
```

### Duplicate toasts

When a toast must appear every time a user clicks a button, use state to render multiple instances of the same toast (see below). Alternatively, you can abstract the parts to create your own [imperative API](/primitives/docs/components/toast#imperative-api).

```jsx
import { createSignal } from "solid-js";

export default () => {

  const [savedCount, setSavedCount] = createSignal(0);

  return <div>

			<form onSubmit={() => setSavedCount(count => count + 1)}>

				{/* ... */}

				<button>save</button>

			</form>



			{Array.from({

      length: savedCount()

    }).map((_, index) => <Toast.Root>

					<Toast.Description>Saved!</Toast.Description>

				</Toast.Root>)}

		</div>;

};
```

### Animating swipe gesture

Combine `--radix-toast-swipe-move-[x|y]` and `--radix-toast-swipe-end-[x|y]` CSS variables with `data-swipe="[start|move|cancel|end]"` attributes to animate a swipe to close gesture. Here's an example:

```jsx
// index.tsx

import { Toast } from "@radix-solid/primitives";

import "./styles.css";

export default () => <Toast.Provider swipeDirection="right">

		<Toast.Root class="ToastRoot">...</Toast.Root>

		<Toast.Viewport />

	</Toast.Provider>;
```

```css
/* styles.css */

.ToastRoot[data-swipe="move"] {

	transform: translateX(var(--radix-toast-swipe-move-x));

}

.ToastRoot[data-swipe="cancel"] {

	transform: translateX(0);

	transition: transform 200ms ease-out;

}

.ToastRoot[data-swipe="end"] {

	animation: slideRight 100ms ease-out;

}



@keyframes slideRight {

	from {

		transform: translateX(var(--radix-toast-swipe-end-x));

	}

	to {

		transform: translateX(100%);

	}

}
```

## Accessibility

Adheres to the [`aria-live` requirements](https://www.w3.org/TR/wai-aria/#aria-live).

### Sensitivity

Control the sensitivity of the toast for screen readers using the `type` prop.

For toasts that are the result of a user action, choose `foreground`. Toasts generated from background tasks should use `background`.

#### Foreground

Foreground toasts are announced immediately. Assistive technologies may choose to clear previously queued messages when a foreground toast appears. Try to avoid stacking distinct foreground toasts at the same time.

#### Background

Background toasts are announced at the next graceful opportunity, for example, when the screen reader has finished reading its current sentence. They do not clear queued messages so overusing them can be perceived as a laggy user experience for screen reader users when used in response to a user interaction.

```jsx
<>

<Toast.Root type="foreground">

	<Toast.Description>File removed successfully.</Toast.Description>

	<Toast.Close>Dismiss</Toast.Close>

</Toast.Root>



<Toast.Root type="background">

	<Toast.Description>We've just released Radix 1.0.</Toast.Description>

	<Toast.Close>Dismiss</Toast.Close>

</Toast.Root>

</>;
```

### Alternative action

Use the `altText` prop on the `Action` to instruct an alternative way of actioning the toast to screen reader users.

You can direct the user to a permanent place in your application where they can action it or implement your own custom hotkey logic. If implementing the latter, use `foreground` type to announce immediately and increase the duration to give the user ample time.

```jsx
<>

<Toast.Root type="background">

	<Toast.Title>Upgrade Available!</Toast.Title>

	<Toast.Description>We've just released Radix 1.0.</Toast.Description>

	<Toast.Action altText="Goto account settings to upgrade">

		Upgrade

	</Toast.Action>

	<Toast.Close>Dismiss</Toast.Close>

</Toast.Root>



<Toast.Root type="foreground" duration={10000}>

	<Toast.Description>File removed successfully.</Toast.Description>

	<Toast.Action altText="Undo (Alt+U)">

		Undo <kbd>Alt</kbd>+<kbd>U</kbd>

	</Toast.Action>

	<Toast.Close>Dismiss</Toast.Close>

</Toast.Root>

</>;
```

### Close icon button

When providing an icon (or font icon), remember to label it correctly for screen reader users.

```jsx
<Toast.Root type="foreground">

	<Toast.Description>Saved!</Toast.Description>

	<Toast.Close aria-label="Close">

		<span aria-hidden="true">×</span>

	</Toast.Close>

</Toast.Root>
```

### Keyboard Interactions

| Key           | Description                                                           |
| ------------- | --------------------------------------------------------------------- |
| `F8`          | Focuses toasts viewport.                                              |
| `Tab`         | Moves focus to the next focusable element.                            |
| `Shift + Tab` | Moves focus to the previous focusable element.                        |
| `Space`       | When focus is on a `Toast.Action` or `Toast.Close`, closes the toast. |
| `Enter`       | When focus is on a `Toast.Action` or `Toast.Close`, closes the toast. |
| `Esc`         | When focus is on a `Toast`, closes the toast.                         |

## Custom APIs

### Abstract parts

Create your own API by abstracting the primitive parts into your own component.

#### Usage

```tsx
import { Toast, ToastProvider, ToastViewport } from "./your-toast";

export default (props: { onUpgrade: () => void }) => <ToastProvider>

  <Toast title="Upgrade available" content="An upgrade is ready to install." actionAltText="Install the available upgrade">

    {target => target("button", { onClick: props.onUpgrade, children: "Upgrade" })}

  </Toast>

  <ToastViewport />

</ToastProvider>;
```

#### Implementation

```jsx
import { omit, type ComponentProps, type Element } from "solid-js";

// your-toast.tsx

import { Toast as ToastPrimitive, Slot } from "@radix-solid/primitives";

export const ToastProvider = ToastPrimitive.Provider;

export const ToastViewport = ToastPrimitive.Viewport;

type Props = Omit<Extract<ComponentProps<typeof ToastPrimitive.Root>, { asChild?: false }>, "title" | "children"> &

  { title?: Element; content: Element } &

  ({ children: Slot.SlotRender; actionAltText: string } | { children?: undefined; actionAltText?: undefined });

export const Toast = (p: Props) => {

  return <ToastPrimitive.Root {...omit(p, "title", "content", "children", "actionAltText")}>

			{p.title && <ToastPrimitive.Title>{p.title}</ToastPrimitive.Title>}

			<ToastPrimitive.Description>{p.content}</ToastPrimitive.Description>

			{p.children && <ToastPrimitive.Action asChild altText={p.actionAltText}>{p.children}</ToastPrimitive.Action>}

			<ToastPrimitive.Close aria-label="Close">

				<span aria-hidden="true">×</span>

			</ToastPrimitive.Close>

		</ToastPrimitive.Root>;

};
```

### Imperative API

Create your own imperative API to allow [toast duplication](/primitives/docs/components/toast#duplicate-toasts) if preferred.

#### Usage

```jsx
import { Toast, ToastProvider, ToastViewport } from './your-imperative-toast';

export default () => {

  let publish!: () => void;

  return <ToastProvider><div><form onSubmit={event => {
      event.preventDefault();
      publish();
    }}><button>Save</button></form>

    <Toast publishRef={callback => {
      publish = callback;
    }}>Saved successfully!</Toast>

  </div><ToastViewport /></ToastProvider>;

};
```

#### Implementation

```tsx
// your-imperative-toast.tsx

import { createSignal, For, onSettled, omit, type ComponentProps } from 'solid-js';

import { Toast as ToastPrimitive } from '@radix-solid/primitives';

export const ToastProvider = ToastPrimitive.Provider;

export const ToastViewport = ToastPrimitive.Viewport;

type Props = Extract<ComponentProps<typeof ToastPrimitive.Root>, { asChild?: false }> & {

  publishRef: (publish: () => void) => void;

};

export function Toast(props: Props) {

  const [count, setCount] = createSignal(0);

  onSettled(() => props.publishRef(() => setCount(value => value + 1)));

  return <For each={Array.from({
    length: count()
  }, (_, index) => index)}>{() => <ToastPrimitive.Root {...omit(props, 'publishRef')}>

    <ToastPrimitive.Description>{props.children}</ToastPrimitive.Description>

    <ToastPrimitive.Close>Dismiss</ToastPrimitive.Close>

  </ToastPrimitive.Root>}</For>;

}
```
