Description:
react-native-alert-queue is a customizable alert system for React Native applications.
It provides a promise-based API that integrates with async/await syntax for managing user interactions.
Features
- ⚡ Promise-based API with async/await support for straightforward alert handling.
- ⏳ Automatic queue management that displays alerts sequentially without conflicts.
- 🛠️ Real-time UI updates that allow dynamic alert content modification while displayed.
- 🎨 Complete customization through custom renderers, slots, and styling options.
- 🖼️ SVG icon integration with configurable size and color properties.
- ⚙️ Global configuration for consistent alert behavior across your application.
- ✅ Pre-built helpers for success dialogs, error messages, and confirmation prompts.
- 🎉 Confetti animation effects for success celebrations and positive user feedback.
- 🌐 React Native Web compatibility for cross-platform implementation.
Use Cases
- User Confirmation: Prompt users to confirm critical actions, such as deleting an item or submitting a form, and wait for their response before proceeding.
- Sequential Notifications: Guide users through a multi-step process by showing a series of informational alerts in a controlled order.
- API Feedback: Display a loading alert while fetching data, then update it to show a success message or an error notification based on the API response.
- Complex Forms: Use alerts with custom components to gather specific user input without navigating to a new screen.
- In-App Announcements: Queue multiple announcements or updates to ensure users see each one without being overwhelmed by simultaneous pop-ups.
How to Use It
1. Installation
npm install react-native-alert-queueOr if you use Yarn:
yarn add react-native-alert-queue2. Add the AlertContainer component to the root of your application, typically in App.tsx. This component handles the rendering of all alerts.
import { AlertContainer } from 'react-native-alert-queue';
import { View } from 'react-native';
function App() {
return (
<View style={{ flex: 1 }}>
{/* Your application's content and navigators */}
<AlertContainer />
</View>
);
}3. To show a simple alert with a title and message, use the alert.show() method.
import { alert } from 'react-native-alert-queue';
const showWelcomeMessage = () => {
alert.show({
title: 'Welcome',
message: 'Thank you for using our application.',
});
};4. The promise-based API allows you to pause function execution until the user interacts with the alert. The alert.confirm() method returns a promise that resolves when a button is pressed.
import { alert } from 'react-native-alert-queue';
const handleDelete = async () => {
const userConfirmed = await alert.confirm({
title: 'Confirm Deletion',
message: 'Are you sure you want to delete this item?',
});
if (userConfirmed) {
// Proceed with the deletion logic
console.log('Item deleted.');
} else {
console.log('Deletion canceled.');
}
};4. You can customize alerts individually or set global styles through the AlertContainer‘s config prop.
Global Configuration
Define a consistent look and feel for all alerts. You can set default styles, icons, and button text.
import { AlertContainer } from 'react-native-alert-queue';
function App() {
return (
<View style={{ flex: 1 }}>
{/* Other components */}
<AlertContainer
config={{
backdropBackgroundColor: 'rgba(0, 0, 0, 0.7)',
alertStyle: {
borderRadius: 12,
backgroundColor: '#FFFFFF',
padding: 24,
},
success: {
title: 'Complete',
},
}}
/>
</View>
);
}Per-Alert Customization
Override global settings or add unique elements for a specific alert. This example uses a custom renderer to change the title’s appearance.
import { alert } from 'react-native-alert-queue';
import { Text } from 'react-native';
const showCustomAlert = () => {
alert.show({
title: 'Special Offer',
message: 'You have unlocked a new badge!',
renderTitle: ({ style, text }) => (
<Text style={[style, { color: 'purple', fontWeight: 'bold' }]}>{text}</Text>
),
buttons: [
{ text: 'Claim', onPress: () => console.log('Badge claimed') },
{ text: 'Later' },
],
});
};API Methods
show(alert: AlertProps): Displays a custom alert.success(alert: AlertProps): Shows a pre-styled success alert.error(error: Error, isFixable?: boolean): Shows a pre-styled error alert.confirm(alert?: ConfirmProps): Displays a confirmation dialog and returns a promise that resolves with the user’s choice.hide(): Hides the alert that is currently visible.clearQueue(hideDisplayedAlert?: boolean): Removes all pending alerts from the queue.update(id: string, alert: AlertProps): Modifies the properties of an existing alert in real-time.getAlertData(id: string): Retrieves the data for a specific alert by its ID.
Alert Props
id?: string: A unique identifier for the alert, used for updates.title?: string: The main title text of the alert.message?: string: The secondary message text displayed below the title.testID?: string: A test identifier for automation purposes.isDismissible?: boolean: Iffalse, the user cannot dismiss the alert by tapping the background.buttonsDirection?: 'row' | 'column': Specifies the layout direction for buttons.icon?: FC<IconProps>: A custom component to use as the alert’s icon.iconColor?: ColorValue: Sets the color of the icon.iconSize?: number: Defines the size of the icon.buttons?: AlertButton[]: An array of button objects to display.confetti?: boolean | ConfettiProps: Enables or configures a confetti animation.renderTitle?: ({ style, text }) => ReactElement: A function to render a custom title component.renderMessage?: ({ style, text }) => ReactElement: A function to render a custom message component.renderButton?: (props) => ReactElement: A function to render custom button components.renderDismissButton?: ({ onPress }) => ReactElement: A function to render a custom dismiss button.beforeTitleSlot?: () => ReactElement: Renders a custom component before the title.beforeMessageSlot?: () => ReactElement: Renders a custom component before the message.beforeButtonsSlot?: () => ReactElement: Renders a custom component before the buttons.afterButtonsSlot?: () => ReactElement: Renders a custom component after the buttons.
AlertButton Props
text: string: The text displayed on the button.onPress?: () => Promise<R> | R: A callback function executed when the button is pressed.disabled?: boolean: Iftrue, the button is not interactive.testID?: string: A test identifier for the button.hideAlertOnPress?: boolean: Iftrue, the alert will close when this button is pressed.onAwaitablePress?: (resolve) => void: A handler for asynchronous operations that resolves the alert’s promise.customProps?: AlertButtonCustomProps: An object for passing additional props to a custom button renderer.
FAQs
Q: Does this library work with Expo?
A: Yes, react-native-alert-queue is compatible with Expo projects. You need to ensure that react-native-reanimated is correctly installed and configured according to the Expo documentation.
Q: How can I prevent an alert from being dismissed when the user taps the background?
A: You can set the isDismissible prop to false when calling an alert. For example alert.show({ message: 'This cannot be dismissed.', isDismissible: false });.
Q: Can I update an alert after it has been displayed?
A: Yes, you can update an alert in real-time. First, provide a unique id when you show the alert. Then, use the alert.update(id, newProps) method to change its title, message, buttons, or other properties.
Q: What is the difference between onPress and onAwaitablePress for buttons?
A: onPress is a standard callback function that executes when a button is tapped. onAwaitablePress is designed for asynchronous operations. It provides a resolve function that you call to close the alert and resolve the promise returned by alert.show().