### Start Example App Packager
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/CONTRIBUTING.md
Starts the Metro server for the example application. Changes in JavaScript code will be reflected without a rebuild.
```sh
yarn example start
```
--------------------------------
### Run Example App on Web
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/CONTRIBUTING.md
Builds and runs the example application on a web browser.
```sh
yarn example web
```
--------------------------------
### Install Dependencies
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/README.md
Run this command to install project dependencies.
```bash
yarn
```
--------------------------------
### Start Local Development Server
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/README.md
Starts a local development server for live preview. Changes are reflected without restarting.
```bash
yarn start
```
--------------------------------
### Run Example App on Android
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/CONTRIBUTING.md
Builds and runs the example application on an Android device or emulator. Native code changes require a rebuild.
```sh
yarn example android
```
--------------------------------
### Run Example App on iOS
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/CONTRIBUTING.md
Builds and runs the example application on an iOS simulator or device. Native code changes require a rebuild.
```sh
yarn example ios
```
--------------------------------
### Install React Native Toast
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/README.md
Install the library using yarn or npm. Ensure peer dependencies like react-native-reanimated, react-native-safe-area-context, and react-native-gesture-handler are also installed.
```sh
yarn add @backpackapp-io/react-native-toast
# or
npm i @backpackapp-io/react-native-toast
```
```sh
yarn add react-native-reanimated react-native-safe-area-context react-native-gesture-handler
```
```sh
npx expo install react-native-reanimated react-native-safe-area-context react-native-gesture-handler
```
--------------------------------
### Install React Native Toast and Dependencies
Source: https://context7.com/backpackapp-io/react-native-toast/llms.txt
Install the package and its peer dependencies using yarn. For Expo projects, use the expo install command.
```sh
yarn add @backpackapp-io/react-native-toast
# Peer dependencies
yarn add react-native-reanimated react-native-safe-area-context react-native-gesture-handler
# Expo
npx expo install react-native-reanimated react-native-safe-area-context react-native-gesture-handler
```
--------------------------------
### Bootstrap Project Dependencies
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/CONTRIBUTING.md
Installs all project dependencies and pods, setting up the development environment.
```sh
yarn bootstrap
```
--------------------------------
### App Setup with GestureHandlerRootView and Toasts
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/getting-started.md
Wrap your root component with GestureHandlerRootView and SafeAreaProvider, and include the Toasts component. This ensures proper toast rendering and gesture handling. Call toast() from anywhere after setup.
```javascript
import { View, StyleSheet, Text } from 'react-native';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { toast, Toasts } from '@backpackapp-io/react-native-toast';
import { useEffect } from 'react';
export default function App() {
useEffect(() => {
toast('Hello');
}, []);
return (
{/*The rest of your app*/} {/* <---- Add Here */}
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
});
```
--------------------------------
### Install React Native Toast with npm
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/index.md
Use this command to add the library to your project using npm.
```bash
npm i @backpackapp-io/react-native-toast
```
--------------------------------
### Full Custom Toast Example
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/api/toast.md
A comprehensive example of a custom toast using JSX, demonstrating dynamic styling and content based on toast properties like height and width. It also shows how to resolve the toast message within the custom component.
```javascript
import { resolveValue } from "@backpackapp-io/react-native-toast";
tost(Math.floor(Math.random() * 1000).toString(), {
width: screenWidth,
disableShadow: true,
customToast: (toast) => {
return (
{resolveValue(toast.message, toast)}
);
},
});
```
--------------------------------
### Install React Native Toast with Yarn
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/index.md
Use this command to add the library to your project using Yarn.
```bash
yarn add @backpackapp-io/react-native-toast
```
--------------------------------
### Basic Usage
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/api/toast.md
Demonstrates the fundamental way to call the toast function with a simple message and an example of a more customized toast with various options.
```APIDOC
## Basic Usage
### Description
Shows how to display a simple toast message and a more advanced toast with custom configurations.
### Method
`toast(message, options?)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **message** (string) - The message to display in the toast.
- **options** (object) - Optional configuration object for the toast.
- **duration** (number) - The duration in milliseconds the toast should be visible. Defaults to a system-defined value.
- **position** (ToastPosition) - The vertical position of the toast (e.g., `ToastPosition.TOP`, `ToastPosition.BOTTOM`).
- **icon** (string) - An icon to display next to the message.
- **animationType** (string) - The type of animation to use ('timing' or 'spring').
- **animationConfig** (object) - Configuration for the toast animation.
- **duration** (number) - Duration of the animation.
- **flingPositionReturnDuration** (number) - Duration for returning to the original position after a fling.
- **easing** (EasingFunction) - Easing function for the animation.
- **customToast** (function) - A function that returns a custom React element for the toast.
- **onPress** (function) - A callback function executed when the toast is pressed.
- **onShow** (function) - A callback function executed when the toast is shown.
- **onHide** (function) - A callback function executed when the toast is hidden, receiving the dismiss reason.
### Request Example
```js
import { toast, ToastPosition, Easing } from '@backpackapp-io/react-native-toast';
// Basic toast
tOast('Hello World');
// Customized toast
tOast('Hello World', {
duration: 4000,
position: ToastPosition.TOP,
icon: '👏',
animationType: 'timing',
animationConfig: {
duration: 500,
flingPositionReturnDuration: 200,
easing: Easing.elastic(1),
},
});
```
### Response
None directly returned, but the toast is displayed on the screen.
```
--------------------------------
### Install Peer Dependencies with Yarn
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/index.md
Install the required peer dependencies for react-native-toast using Yarn.
```bash
yarn add react-native-reanimated react-native-safe-area-context react-native-gesture-handler
```
--------------------------------
### Install Peer Dependencies with Expo
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/index.md
Install the required peer dependencies for react-native-toast when using Expo.
```bash
npx expo install react-native-reanimated react-native-safe-area-context react-native-gesture-handler
```
--------------------------------
### Component-Specific Logic with Toast
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/api/toast.md
Use individual handlers to access component-specific state, hooks, or navigation when displaying toasts. This example shows how to cancel an order and navigate after a toast interaction.
```javascript
const OrderConfirmationScreen = () => {
const navigation = useNavigation();
const { orderId } = useRoute().params;
const { mutate: cancelOrder } = useCancelOrderMutation();
const showUndoToast = () => {
toast('Order placed!', {
onPress: () => {
// Access component-specific state and functions
cancelOrder(orderId);
navigation.navigate('OrderCanceled');
},
duration: 5000,
});
};
return (
);
};
```
--------------------------------
### Accessing Active Toasts
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/api/use-toaster.md
Retrieve the array of currently active toasts managed by the useToaster hook. This example logs the toasts array to the console.
```js
const { toasts } = useToaster();
console.log(toasts); // [{ id: '1', message: 'Toast 1', ... }]
```
--------------------------------
### Display a Loading Toast and Dismiss Manually
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/getting-started.md
Show a toast that indicates a loading state and can be manually dismissed. Use the returned ID to dismiss the toast later, for example, after a timeout.
```javascript
const id = toast.loading('I am loading. Dismiss me whenever...');
setTimeout(() => {
toast.dismiss(id);
}, 3000);
```
--------------------------------
### Build Static Website
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/README.md
Generates the static content for the website into the 'build' directory.
```bash
yarn build
```
--------------------------------
### Basic Toast Usage
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/api/toast.md
Demonstrates how to display a simple toast message with optional configurations like duration and position.
```APIDOC
## Basic Toast
### Description
Displays a simple toast message.
### Method
tost
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **message** (string) - Required - The message to display in the toast.
- **options** (object) - Optional - Configuration options for the toast.
- **duration** (number) - Optional - The duration in milliseconds the toast should be visible. Defaults vary by type.
- **position** (string) - Optional - The position of the toast (e.g., 'top', 'bottom').
- **isSwipeable** (boolean) - Optional - Whether the toast can be dismissed by swiping. Defaults to true.
- **disableShadow** (boolean) - Optional - Whether to disable the shadow effect of the toast. Defaults to false.
- **styles** (object) - Optional - Custom styles to apply to the toast.
- **animationType** (string) - Optional - The type of animation to use ('spring', 'timing').
- **animationConfig** (object) - Optional - Configuration for the toast animation.
### Request Example
```js
tost('This is a basic toast message');
tost('Toast with custom duration and position', {
duration: 3000,
position: 'bottom'
});
```
### Response
#### Success Response (200)
None
#### Response Example
None
```
--------------------------------
### Deploy Website (No SSH)
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/README.md
Deploys the website without using SSH. Requires specifying your GitHub username.
```bash
GIT_USER= yarn deploy
```
--------------------------------
### Simple Toast with Individual Handlers
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/features/toast-handlers.md
Shows how to attach individual handlers for toast events like showing, hiding, and pressing. Useful for tracking toast lifecycle and user interactions.
```jsx
import { toast, DismissReason } from '@backpackapp-io/react-native-toast';
// Simple toast with individual handlers
toa('Operation completed', {
onShow: (toast) => {
console.log(`Toast ${toast.id} appeared`);
analytics.track('toast_shown', { id: toast.id });
},
onHide: (toast, reason) => {
console.log(`Toast ${toast.id} disappeared because: ${reason}`);
analytics.track('toast_hidden', { id: toast.id, reason });
},
onPress: (toast) => {
console.log(`Toast ${toast.id} was pressed`);
navigation.navigate('Details');
}
});
```
--------------------------------
### Toast Handlers and Dismiss Reasons
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/api/toast.md
Details how to use `onPress`, `onShow`, and `onHide` handlers for individual toasts, and explains the different `DismissReason` values.
```APIDOC
## Toast Handlers and Dismiss Reasons
### Description
Explains how to attach event handlers (`onPress`, `onShow`, `onHide`) to individual toasts for interactive behavior and logging. It also details the possible reasons a toast might be dismissed.
### Method
`toast(message, options?)`
### Parameters
- **message** (string) - The message for the toast.
- **options** (object)
- **onPress** (function) - Callback when the toast is pressed. Receives the `toast` object.
- **onShow** (function) - Callback when the toast is displayed. Receives the `toast` object.
- **onHide** (function) - Callback when the toast is dismissed. Receives the `toast` object and a `reason`.
#### Dismiss Reasons
| Reason | Description |
|--------|-------------|
| `DismissReason.TIMEOUT` | The toast was dismissed because its duration elapsed. |
| `DismissReason.SWIPE` | The toast was dismissed because the user swiped it away. |
| `DismissReason.PROGRAMMATIC` | The toast was dismissed programmatically via `toast.dismiss()`. |
| `DismissReason.TAP` | The toast was dismissed because the user tapped it. |
### Request Example
```js
import { DismissReason } from '@backpackapp-io/react-native-toast';
const id = toast('Hello World', {
onPress: (toast) => {
console.log('Toast pressed!', toast.id);
// navigation.navigate('Details', { id: toast.id });
},
onShow: (toast) => {
console.log('Toast shown!', toast.id);
// analytics.logEvent('toast_shown', { id: toast.id });
},
onHide: (toast, reason) => {
console.log(`Toast ${toast.id} dismissed because: ${reason}`);
switch(reason) {
case DismissReason.TIMEOUT:
console.log('Toast timed out');
break;
case DismissReason.SWIPE:
console.log('User swiped toast away');
break;
case DismissReason.PROGRAMMATIC:
console.log('Toast was programmatically dismissed');
break;
case DismissReason.TAP:
console.log('User tapped to dismiss toast');
break;
}
}
});
```
### Response
None directly returned, but the toast is displayed and its associated handlers are invoked upon the corresponding events.
```
--------------------------------
### Importing useToaster
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/api/use-toaster.md
Import the useToaster hook from the library.
```tsx
import { useToaster } from '@backpackapp-io/react-native-toast';
```
--------------------------------
### Publish New Versions with Release-it
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/CONTRIBUTING.md
Uses release-it to automate the process of bumping versions, creating tags, and publishing new releases to npm.
```sh
yarn release
```
--------------------------------
### Custom Toast Animation Configuration
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/features/animations.md
Shows how to customize animation parameters like duration and fling return duration for 'timing' animations, and advanced spring physics for 'spring' animations.
```javascript
toast('Custom Animation', {
animationType: 'timing',
animationConfig: {
duration: 500,
flingPositionReturnDuration: 500,
},
});
```
```javascript
toast('Custom Spring Animation', {
animationType: 'spring',
animationConfig: {
damping: 10,
stiffness: 80,
mass: 0.8,
overshootClamping: false,
restDisplacementThreshold: 0.01,
restSpeedThreshold: 0.01,
duration: 500, // Note: you can still use duration which won't affect the spring animation but the opacity fade in/out
},
});
```
--------------------------------
### Deploy Website (SSH)
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/README.md
Deploys the website using SSH, typically for pushing to a 'gh-pages' branch.
```bash
USE_SSH=true yarn deploy
```
--------------------------------
### Loading Toast
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/api/toast.md
Shows how to display a loading toast, which is typically used to indicate an ongoing process. It can be dismissed programmatically.
```APIDOC
## Loading Toast
### Description
Displays a toast indicating a loading state. Returns an ID that can be used to dismiss or update the toast.
### Method
tost.loading
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **message** (string) - Required - The message to display in the loading toast.
- **options** (object) - Optional - Configuration options for the toast.
### Request Example
```js
const id = tost.loading('Waiting for data...');
// Later, to dismiss:
tost.dismiss(id);
```
### Response
#### Success Response (200)
- **id** (string) - The unique identifier for the loading toast.
#### Response Example
```json
{
"id": "some-unique-toast-id"
}
```
```
--------------------------------
### Toast Options
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/api/toast.md
The `toast()` function accepts an options object to customize its behavior and appearance.
```APIDOC
## Toast Options
### Description
Customize toast messages using the following options:
### Parameters
#### Toast Options Object
- **`duration`** (number) - Optional - Default: `3000` - Duration in milliseconds. Set to `Infinity` to keep the toast open until dismissed manually.
- **`position`** (enum) - Optional - Default: `1` - Position of the toast. Can be `ToastPosition.{TOP, BOTTOM, TOP_LEFT, BOTTOM_LEFT, TOP_RIGHT, BOTTOM_RIGHT}`.
- **`id`** (string) - Optional - Unique id for the toast.
- **`icon`** (Element) - Optional - Icon to display on the left of the toast.
- **`animationType`** (string) - Optional - Default: `'timing'` - Animation type. Can be 'timing' or 'spring'.
- **`animationConfig`** (object) - Optional - Animation configuration.
- **`customToast`** (function) - Optional - Custom toast component.
- **`width`** (number) - Optional - Width of the toast.
- **`height`** (number) - Optional - Height of the toast.
- **`disableShadow`** (boolean) - Optional - Default: `false` - Disable shadow on the toast.
- **`isSwipeable`** (boolean) - Optional - Default: `true` - Disable/Enable swipe to dismiss the toast.
- **`providerKey`** (string) - Optional - Default: `'DEFAULT'` - Provider key for the toast.
- **`accessibilityMessage`** (string) - Optional - Accessibility message for screen readers.
- **`styles`** (object) - Optional - Styles for the toast.
- **`onShow`** (function) - Optional - Function called when this specific toast is shown.
- **`onHide`** (function) - Optional - Function called when this specific toast is hidden, with dismiss reason.
- **`onPress`** (function) - Optional - Function called when this specific toast is pressed.
```
--------------------------------
### Custom Toast (JSX)
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/api/toast.md
Shows how to create a fully custom toast using JSX, giving you complete control over its appearance and content.
```APIDOC
## Custom Toast (JSX)
### Description
Enables the creation of highly customized toasts using React elements. This allows for complete control over the toast's appearance and content.
### Method
`toast(message, options?)`
### Parameters
- **message** (string) - The message to display. Can be used by `resolveValue` within `customToast`.
- **options** (object)
- **customToast** (function) - A function that receives toast data and returns a React element to be rendered as the toast.
- Other options like `width`, `disableShadow`, etc., can also be applied.
### Request Example
```js
import { resolveValue } from '@backpackapp-io/react-native-toast';
import { View, Text } from 'react-native';
tOast('', {
customToast: (toast) => (
{resolveValue(toast.message, toast)}
)
});
// Full example with styling and dynamic message
const screenWidth = Dimensions.get('window').width;
tOast(Math.floor(Math.random() * 1000).toString(), {
width: screenWidth,
disableShadow: true,
customToast: (toast) => {
return (
{resolveValue(toast.message, toast)}
);
},
});
```
### Response
None directly returned, but the custom toast component is rendered on the screen.
```
--------------------------------
### Basic Toast Usage
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/api/toast.md
Import the toast function and call it with a message. For more control, pass an options object with properties like duration, position, icon, and animation settings.
```javascript
import { toast } from '@backpackapp-io/react-native-toast';
// ...
tost('Hello World');
// ...
tost('Hello World', {
duration: 4000,
position: ToastPosition.TOP,
icon: '👏',
animationType: 'timing',
animationConfig: {
duration: 500,
flingPositionReturnDuration: 200,
easing: Easing.elastic(1),
},
});
```
--------------------------------
### Toast with Undo Functionality
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/features/toast-handlers.md
Shows how to implement an 'undo' feature for a toast, where pressing the toast triggers a restore action and dismisses the toast. It also includes logic to permanently delete if not undone.
```jsx
function EmailList() {
const { deleteEmail, restoreEmail } = useEmails();
const handleDelete = (emailId) => {
// Delete the email
deleteEmail(emailId);
// Show toast with undo button
toast('Email deleted', {
duration: 5000,
onPress: (toast) => {
// Restore the email when toast is pressed
restoreEmail(emailId);
// Dismiss the toast
toast.dismiss(toast.id);
// Show confirmation
toast.success('Email restored');
},
// Can also check dismiss reason
onHide: (toast, reason) => {
if (reason !== DismissReason.TAP) {
// If toast wasn't tapped (undo wasn't clicked),
// permanently delete the email
console.log('Email permanently deleted');
}
}
});
};
return (
(
handleDelete(item.id)}
/>
)}
/>
);
}
```
--------------------------------
### Individual vs Global Toast Handlers
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/api/toast.md
Demonstrates how to use both individual toast handlers (specific to a single toast) and global handlers (applied to all toasts via the `` component). When both are present, both handlers will execute.
```javascript
// Individual handler (specific to this toast)
tost('Hello', {
onPress: (toast) => {
// This runs only for this specific toast
console.log('This specific toast was pressed');
}
});
// In your app component
{
// This runs for ALL toasts
console.log('A toast was pressed:', toast.id);
}}
/>
```
--------------------------------
### Custom Toast Handling with useToaster
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/api/use-toaster.md
Demonstrates advanced usage by combining useToaster with a custom component to perform actions based on toast messages, such as logging errors.
```tsx
import React from 'react';
import { useToaster } from '@backpackapp-io/react-native-toast';
export const CustomToaster = () => {
const { toasts } = useToaster();
useEffect(() => {
toasts.forEach((toast) => {
if(toast.id === 'ERROR') {
console.error(toast.message);
}
});
}, [toasts]);
};
```
--------------------------------
### On Toast Show Callback
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/components/toasts.md
Callback function that fires when a toast is shown.
```APIDOC
## onToastShow
### Description
When a toast is shown, this callback will fire, returning the toast object that was shown. _Note, the toast object is "shown" when the toast is mounted._
### Type
`function`
### Signature
```typescript
onToastShow?: (toast: T) => void;
```
```
--------------------------------
### Subscribe to Toast State with `useToasterStore()`
Source: https://context7.com/backpackapp-io/react-native-toast/llms.txt
The `useToasterStore` hook directly subscribes to the global toast store state. It's useful for syncing toast state into external state management or reacting to all toast changes.
```tsx
import { useToasterStore, toast } from '@backpackapp-io/react-native-toast';
import { useEffect } from 'react';
const ToastMonitor = ({ isModalVisible }: { isModalVisible: boolean }) => {
const { toasts } = useToasterStore();
// Re-assign all toasts to a new providerKey when a modal opens
useEffect(() => {
toasts.forEach((t) => {
toast(t.message, {
...t,
providerKey: isModalVisible ? 'MODAL::1' : 'DEFAULT',
});
});
}, [isModalVisible]);
return null;
};
```
--------------------------------
### Extra Insets
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/components/toasts.md
Supply the toast container with extra padding.
```APIDOC
## extraInsets
### Description
Supply the container for the toasts with extra padding.
### Type
`object`
### Structure
```typescript
extraInsets?: {
top?: number;
bottom?: number;
right?: number;
left?: number;
};
```
```
--------------------------------
### Default Styles
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/components/toasts.md
Supply default styles for the toast component, which will be applied to all toasts unless overridden.
```APIDOC
## defaultStyle
### Description
Supply default styles for the toast component. This will be applied to all toasts unless overridden by the toast options.
### Type
`object`
### Structure
```typescript
defaultStyle?: {
view?: ViewStyle;
pressable?: ViewStyle;
text?: TextStyle;
indicator?: ViewStyle;
};
```
```
--------------------------------
### Lint Code with ESLint
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/CONTRIBUTING.md
Runs ESLint to check for code style and potential errors.
```sh
yarn lint
```
--------------------------------
### Programmatically Dismissing with Reason
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/features/toast-handlers.md
Demonstrates how to programmatically dismiss toasts using `toast.dismiss()` and optionally provide a reason. This is useful for managing toast states during asynchronous operations like uploads.
```jsx
function UploadScreen() {
const [uploadId, setUploadId] = useState(null);
const startUpload = async () => {
// Show loading toast
const id = toast.loading('Uploading file...');
setUploadId(id);
try {
await uploadFile();
// Success - update toast
toast.success('Upload complete!', { id });
} catch (error) {
// Error - dismiss with custom reason
toast.dismiss(id, DismissReason.PROGRAMMATIC);
// Show error toast
toast.error('Upload failed');
}
};
const cancelUpload = () => {
if (uploadId) {
// Dismiss with custom reason
toast.dismiss(uploadId, DismissReason.PROGRAMMATIC);
toast('Upload cancelled');
}
};
return (
);
}
```
--------------------------------
### Run Unit Tests with Jest
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/CONTRIBUTING.md
Executes the unit tests for the project using Jest. All tests must pass for merging.
```sh
yarn test
```
--------------------------------
### Global Animation Configuration
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/components/toasts.md
Set the global animation configuration for all toasts. This can be overridden by individual toast options.
```APIDOC
## globalAnimationConfig
### Description
Set the global animation config for all toasts. This can be overridden by the toast options.
### Type
`object`
### Example
```jsx
```
```
--------------------------------
### On Toast Press Callback
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/components/toasts.md
Callback function that fires when a toast is pressed.
```APIDOC
## onToastPress
### Description
When a toast is pressed, this callback will fire, returning the toast object that was pressed.
### Type
`function`
### Signature
```typescript
onToastPress?: (toast: T) => void;
```
```
--------------------------------
### Manage Multiple Toasts with `providerKey`
Source: https://context7.com/backpackapp-io/react-native-toast/llms.txt
Use unique `providerKey` values to manage multiple `` instances. Toast calls target a specific instance via the `providerKey` option. Use `'PERSISTS'` to make a toast visible across all instances.
```tsx
import { Toasts, toast } from '@backpackapp-io/react-native-toast';
// Root layout
// providerKey defaults to "DEFAULT"
// Only renders toasts tagged MODAL::AUTH
// Targeted calls
toa st('Welcome back!'); // shows in DEFAULT
toa st('Verify your email', { providerKey: 'MODAL::AUTH' }); // shows in modal only
toa st('Global alert', { providerKey: 'PERSISTS' }); // shows in ALL instances
```
--------------------------------
### Customizing Toast Behavior
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/api/toast.md
Details various options for customizing toast behavior, including swipe gestures, shadows, and animations.
```APIDOC
## Prevent Swipe to Dismiss
### Description
Disables the swipe-to-dismiss gesture for a toast.
### Method
tost
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **message** (string) - Required - The message to display.
- **options** (object) - Optional - Configuration options for the toast.
- **isSwipeable** (boolean) - Required - Set to `false` to disable swiping. Defaults to `true`.
- **duration** (number) - Optional - The duration in milliseconds the toast should be visible.
- **position** (string) - Optional - The position of the toast.
### Request Example
```js
tost('This toast cannot be swiped away', {
isSwipeable: false,
duration: 4000,
position: 'top'
});
```
### Response
#### Success Response (200)
None
#### Response Example
None
```
```APIDOC
## Disable Shadow
### Description
Disables the shadow effect applied to the toast.
### Method
tost
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **message** (string) - Required - The message to display.
- **options** (object) - Optional - Configuration options for the toast.
- **disableShadow** (boolean) - Required - Set to `true` to disable the shadow. Defaults to `false`.
- **duration** (number) - Optional - The duration in milliseconds the toast should be visible.
- **position** (string) - Optional - The position of the toast.
### Request Example
```js
tost('This toast has no shadow', {
disableShadow: true,
duration: 4000,
position: 'top'
});
```
### Response
#### Success Response (200)
None
#### Response Example
None
```
```APIDOC
## Animation Options
### Description
Controls the animation type and configuration for toasts.
### Method
tost
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **message** (string) - Required - The message to display.
- **options** (object) - Optional - Configuration options for the toast.
- **animationType** (string) - Optional - The type of animation to use ('spring' or 'timing').
- **animationConfig** (object) - Optional - Configuration for the toast animation.
- **duration** (number) - Optional - The duration of the opacity animation in milliseconds.
- **stiffness** (number) - Optional - The stiffness of the spring animation.
- **duration** (number) - Required - The total duration of the toast in milliseconds.
- **position** (string) - Optional - The position of the toast.
### Request Example
```js
tost('This is a toast message', {
animationType: 'spring',
animationConfig: {
duration: 500,
stiffness: 100,
},
duration: 3000,
position: 'top'
});
```
### Response
#### Success Response (200)
None
#### Response Example
None
```
--------------------------------
### Toast Animation Types
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/features/animations.md
Demonstrates how to use different animation types for toast notifications: 'spring', 'fade', and the default 'timing'.
```javascript
toast('Spring Animation', {
animationType: 'spring',
});
ttoast('Fade Animation', {
animationType: 'fade',
});
ttoast('Default Timing Animation');
```
--------------------------------
### Toast Lifecycle Callbacks and `DismissReason`
Source: https://context7.com/backpackapp-io/react-native-toast/llms.txt
Each toast can carry `onShow`, `onHide`, and `onPress` callbacks. `onHide` receives a `DismissReason` enum value indicating why the toast was dismissed: `TIMEOUT`, `SWIPE`, `PROGRAMMATIC`, or `TAP`.
```APIDOC
## Toast Lifecycle Callbacks and `DismissReason`
Each toast can carry `onShow`, `onHide`, and `onPress` callbacks. `onHide` receives a `DismissReason` enum value indicating why the toast was dismissed: `TIMEOUT`, `SWIPE`, `PROGRAMMATIC`, or `TAP`.
```tsx
import { toast, DismissReason } from '@backpackapp-io/react-native-toast';
tost('Order placed!', {
duration: 5000,
onShow: (t) => {
analytics.track('toast_shown', { id: t.id });
},
onHide: (t, reason) => {
if (reason === DismissReason.SWIPE) {
analytics.track('toast_swiped_away', { id: t.id });
}
if (reason === DismissReason.TIMEOUT) {
console.log('Toast auto-dismissed');
}
},
onPress: (t) => {
navigation.navigate('OrderDetails', { orderId: t.id });
},
});
```
```
--------------------------------
### Set Global Animation Configuration
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/components/toasts.md
Define the global animation configuration for all toasts. Individual toasts can override these settings.
```javascript
```
--------------------------------
### Displaying a Loading Toast
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/api/toast.md
Show a loading notification using `toast.loading`. Remember to dismiss it later using `toast.dismiss(id)` or use `toast.promise()` for automatic handling.
```javascript
const id = toast.loading('Waiting...');
//Somewhere later in your code...
tost.dismiss(id);
```
--------------------------------
### Positioning (`ToastPosition`)
Source: https://context7.com/backpackapp-io/react-native-toast/llms.txt
Six positions are available via the `ToastPosition` enum. Can be set globally on `` or per toast call.
```APIDOC
## Positioning (`ToastPosition`)
Six positions are available via the `ToastPosition` enum. Can be set globally on `` or per toast call.
```tsx
import { toast, ToastPosition } from '@backpackapp-io/react-native-toast';
tost('Top center', { position: ToastPosition.TOP });
tost('Bottom center', { position: ToastPosition.BOTTOM });
tost('Top left', { position: ToastPosition.TOP_LEFT });
tost('Top right', { position: ToastPosition.TOP_RIGHT });
tost('Bottom left', { position: ToastPosition.BOTTOM_LEFT });
tost('Bottom right', { position: ToastPosition.BOTTOM_RIGHT });
// Or set globally with a per-toast override
// This toast overrides the global default:
tost('Override to top', { position: ToastPosition.TOP });
```
```
--------------------------------
### Toast Handlers and Dismiss Reasons
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/api/toast.md
Implement `onPress`, `onShow`, and `onHide` handlers for detailed control over toast behavior and responses. The `onHide` handler receives a `reason` argument, allowing you to differentiate between timeout, swipe, programmatic dismissal, or tap.
```javascript
import { DismissReason } from "@backpackapp-io/react-native-toast";
const id = toast('Hello World', {
// Handler for when toast is pressed
onPress: (toast) => {
console.log('Toast pressed!', toast.id);
// Access component-specific methods or state here
navigation.navigate('Details', { id: toast.id });
},
// Handler for when toast appears
onShow: (toast) => {
console.log('Toast shown!', toast.id);
analytics.logEvent('toast_shown', { id: toast.id });
},
// Handler for when toast is dismissed with reason
onHide: (toast, reason) => {
console.log(`Toast ${toast.id} dismissed because: ${reason}`);
// Handle different dismiss reasons
switch(reason) {
case DismissReason.TIMEOUT:
console.log('Toast timed out');
break;
case DismissReason.SWIPE:
console.log('User swiped toast away');
break;
case DismissReason.PROGRAMMATIC:
console.log('Toast was programmatically dismissed');
break;
case DismissReason.TAP:
console.log('User tapped to dismiss toast');
break;
}
}
});
```
--------------------------------
### Display a Success Toast
Source: https://context7.com/backpackapp-io/react-native-toast/llms.txt
Use toast.success() to create a toast with a green indicator bar. Custom styles can be applied, and an ID can be provided to prevent duplicates.
```tsx
import { toast } from '@backpackapp-io/react-native-toast';
tost.success('Payment confirmed!', {
duration: 3000,
id: 'payment-success', // prevent duplicate if called multiple times
styles: {
text: { fontWeight: 'bold' },
},
});
```
--------------------------------
### toast.loading() — Loading Toast
Source: https://context7.com/backpackapp-io/react-native-toast/llms.txt
Displays a persistent loading toast, which does not dismiss automatically (duration defaults to `Infinity`). This toast must be manually dismissed or updated using its ID.
```APIDOC
## toast.loading() — Loading Toast
### Description
Creates a persistent loading toast (duration defaults to `Infinity`). Must be manually dismissed or updated.
### Usage
```tsx
import { toast } from '@backpackapp-io/react-native-toast';
const id = toast.loading('Uploading file...');
try {
await uploadFile(file);
toast.success('Upload complete!', { id }); // updates the existing toast
} catch (e) {
toast.error('Upload failed', { id });
}
```
### Parameters
- **message** (string) - The loading message to display.
- **options** (object, optional) - Configuration options, same as `toast()`. The `duration` defaults to `Infinity`.
```
--------------------------------
### Promise Toast (`toast.promise()`)
Source: https://context7.com/backpackapp-io/react-native-toast/llms.txt
Automatically manages a loading → success/error lifecycle for a Promise. The `success` and `error` message fields accept either a string or a function receiving the resolved value or rejection reason.
```APIDOC
## `toast.promise()` — Promise Toast
Automatically manages a loading → success/error lifecycle for a Promise. The `success` and `error` message fields accept either a string or a function receiving the resolved value or rejection reason.
```tsx
import { toast, ToastPosition } from '@backpackapp-io/react-native-toast';
const saveUser = async (userData) => {
const response = await fetch('/api/users', {
method: 'POST',
body: JSON.stringify(userData),
});
if (!response.ok) throw new Error('Server error');
return response.json();
};
tost.promise(
saveUser({ name: 'Alice', email: 'alice@example.com' }),
{
loading: 'Saving user...',
success: (data) => `User ${data.name} saved!`,
error: (err) => `Error: ${err.message}`
},
{
position: ToastPosition.BOTTOM,
duration: 3000,
}
);
```
```
--------------------------------
### Toast Lifecycle Callbacks and Dismiss Reason
Source: https://context7.com/backpackapp-io/react-native-toast/llms.txt
Utilize `onShow`, `onHide`, and `onPress` callbacks for each toast. The `onHide` callback receives a `DismissReason` enum value indicating why the toast was dismissed.
```tsx
import { toast, DismissReason } from '@backpackapp-io/react-native-toast';
tost('Order placed!', {
duration: 5000,
onShow: (t) => {
analytics.track('toast_shown', { id: t.id });
},
onHide: (t, reason) => {
if (reason === DismissReason.SWIPE) {
analytics.track('toast_swiped_away', { id: t.id });
}
if (reason === DismissReason.TIMEOUT) {
console.log('Toast auto-dismissed');
}
},
onPress: (t) => {
navigation.navigate('OrderDetails', { orderId: t.id });
},
});
```
--------------------------------
### Handling Different Dismiss Reasons
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/features/toast-handlers.md
Demonstrates how to use the onHide handler to react to different reasons a toast might be dismissed, such as timeout, swipe, tap, or programmatic dismissal.
```jsx
toast.success('Item added to cart', {
onHide: (toast, reason) => {
switch (reason) {
case DismissReason.TIMEOUT:
// User didn't interact with the toast
console.log('User didn\'t interact with cart notification');
break;
case DismissReason.SWIPE:
// User actively dismissed the toast
console.log('User dismissed cart notification');
break;
case DismissReason.TAP:
// User tapped the toast
console.log('User tapped cart notification');
break;
case DismissReason.PROGRAMMATIC:
// Toast was dismissed by code
console.log('Cart notification was programmatically dismissed');
break;
}
}
});
```
--------------------------------
### Verify Code with TypeScript
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/CONTRIBUTING.md
Runs TypeScript to check for type errors in the codebase.
```sh
yarn typescript
```
--------------------------------
### Custom Animated Loading Spinner with Toast
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/features/animations.md
Illustrates creating a custom React Native component for a loading spinner within a toast notification, utilizing Reanimated for animations.
```javascript
const LoadingMessage = ({ msg }: { msg: string }) => {
const isDarkMode = useColorScheme() === 'dark';
return (
{msg}
);
};
ttoast.loading(, {
animationType: 'timing',
animationConfig: {
duration: 500,
flingPositionReturnDuration: 500,
},
})
```
```javascript
toast.promise(
new Promise((resolve) => {
setTimeout(() => {
resolve('Promise resolved')
}, 2000)
}),
{
loading: ,
success: 'Promise resolved',
error: 'Promise rejected',
animationType: 'timing',
animationConfig: {
duration: 500,
flingPositionReturnDuration: 500,
},
}
);
```
--------------------------------
### toast.success() — Success Toast
Source: https://context7.com/backpackapp-io/react-native-toast/llms.txt
Creates a toast with a green success indicator bar on the left side. Useful for confirming successful operations.
```APIDOC
## toast.success() — Success Toast
### Description
Creates a toast with a green success indicator bar on the left side.
### Usage
```tsx
import { toast } from '@backpackapp-io/react-native-toast';
tost.success('Payment confirmed!', {
duration: 3000,
id: 'payment-success', // prevent duplicate if called multiple times
styles: {
text: { fontWeight: 'bold' },
},
});
```
### Parameters
- **message** (string) - The success message to display.
- **options** (object, optional) - Configuration options, same as `toast()`.
```
--------------------------------
### Success Toast
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/api/toast.md
Creates a notification with a success indicator on the left. Use this to inform users of successful operations.
```javascript
toast.success('Successfully created!');
```
--------------------------------
### Use `useToaster()` Hook for Custom UIs
Source: https://context7.com/backpackapp-io/react-native-toast/llms.txt
The `useToaster` hook provides access to the raw toast array and lifecycle handlers, enabling the creation of fully custom toast UIs. It exposes `toasts` and `handlers` for managing toast state and interactions.
```tsx
import { useToaster, toast } from '@backpackapp-io/react-native-toast';
import { useEffect } from 'react';
const ToastDebugger = () => {
const { toasts, handlers } = useToaster();
useEffect(() => {
toasts.forEach((t) => {
if (t.type === 'error') {
console.error('[Toast Error]', t.id, t.message);
}
});
}, [toasts]);
return null;
};
// handlers API:
// handlers.startPause() — pause all timers
// handlers.endPause() — resume all timers
// handlers.updateHeight(toastId, height) — notify height change
// handlers.calculateOffset(toast, opts) — compute stacking offset
```
--------------------------------
### Configure Global Toast Settings
Source: https://github.com/backpackapp-io/react-native-toast/blob/master/website/docs/components/toasts.md
Configure global settings for the Toasts component, including press handlers, dark mode overrides, animation types and configurations, default positions, and default durations.
```javascript
import { Toasts, ToastPosition } from '@backpackapp-io/react-native-toast';
{
console.log(`Toast ${t.id} was pressed. `)
}}
overrideDarkMode={isAppDarkMode}
globalAnimationType="fade"
globalAnimationConfig={{duration: 500}}
defaultPosition={ToastPosition.BOTTOM}
defaultDuration={4000}
/>
```