Skip to content

About

A custom-built component that replicates the functionality of the React Native Alert, providing the same behavior with additional styling and customization options.

Resources

Code of conduct

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

globalAlert

Features

  • 🚀 Global Access - Show alerts from anywhere in your app
  • 📱 React Native Optimized - Built specifically for React Native
  • 🎯 Priority System - HIGH alerts wait their turn (first in, first out); LOW alerts are best-effort
  • 🎨 Fully Customizable - Custom styling and alert components
  • ⚡ TypeScript Support - Full type safety out of the box
  • 🔄 Smart Queue Management - Intelligent alert queuing with priority handling
  • 🪝 React Hooks - Modern React patterns with useGlobalAlert hook
  • 🎭 Multiple Alert Types - Error, Warning, Success, Info, Notice, Question, Loading, and Tips
  • ⚙️ Flexible Configuration - Optional priority enforcement and backdrop dismiss
  • 📚 Multiple Alerts - Show multiple alerts in sequence with showMultiple
  • 🎨 Button Customization - Rich button styling and behavior options
  • ⏱️ Auto Dismiss & Countdown - Close alerts automatically with dismissIn, show the remaining seconds with useAlertCountdown, extend or cancel the timer with update
  • 🔁 Live Updates - Change the alert that is on screen with update (great for progress/loading)
  • 🧘 Render Friendly - Showing or hiding an alert only re-renders your modal, never your app tree

Requirements

  • React 18 or newer (React Native 0.69+)

Installation

npm install @hexhad/react-native-global-modal

or

yarn add @hexhad/react-native-global-modal

Quick Start

1. Setup the Provider

Wrap your app with GlobalAlertProvider and provide your custom alert modal component:

import React from 'react';
import { GlobalAlertProvider, GlobalAlert } from '@hexhad/react-native-global-modal';
import CustomAlertModal from './components/CustomAlertModal';

export default function App() {
  return (
    <GlobalAlertProvider 
      AlertModal={CustomAlertModal}
      ignorePriority={false} // Optional: set to true to always show latest alert
    >
      {/* Your app content */}
    </GlobalAlertProvider>
  );
}

2. Create Your Alert Modal Component

import React from 'react';
import { Modal, View, Text, TouchableOpacity, StyleSheet } from 'react-native';
import type { AlertModalProps } from '@hexhad/react-native-global-modal';

const CustomAlertModal: React.FC<AlertModalProps> = ({ visible, data, onClose }) => {
  if (!data) return null;

  return (
    <Modal 
      visible={visible} 
      transparent 
      animationType="fade"
      onRequestClose={data.backdropDismiss ? onClose : undefined}
    >
      <TouchableOpacity 
        style={styles.overlay}
        activeOpacity={1}
        onPress={data.backdropDismiss ? onClose : undefined}
      >
        <TouchableOpacity style={styles.container} activeOpacity={1}>
          {data.title && <Text style={styles.title}>{data.title}</Text>}
          {data.message && <Text style={styles.message}>{data.message}</Text>}
          
          <View style={styles.buttonContainer}>
            {data.buttons?.map((button, index) => (
              <TouchableOpacity
                key={index}
                style={[styles.button, button.style, { backgroundColor: getButtonColor(button.variant) }]}
                onPress={() => {
                  button.onPress?.();
                  if (button.closeOnPress !== false) {
                    onClose?.();
                  }
                }}
              >
                <Text style={[styles.buttonText, button.textStyle]}>{button.title}</Text>
              </TouchableOpacity>
            ))}
          </View>
        </TouchableOpacity>
      </TouchableOpacity>
    </Modal>
  );
};

const getButtonColor = (variant?: string) => {
  switch (variant) {
    case 'ERROR': return '#FF6B6B';
    case 'SUCCESS': return '#51CF66';
    case 'WARNING': return '#FFD93D';
    default: return '#339AF0';
  }
};

const styles = StyleSheet.create({
  overlay: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  container: {
    backgroundColor: 'white',
    borderRadius: 12,
    padding: 20,
    margin: 20,
    minWidth: 280,
  },
  title: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 10,
    textAlign: 'center',
  },
  message: {
    fontSize: 16,
    marginBottom: 20,
    textAlign: 'center',
    color: '#666',
  },
  buttonContainer: {
    flexDirection: 'row',
    justifyContent: 'space-around',
  },
  button: {
    paddingHorizontal: 20,
    paddingVertical: 10,
    borderRadius: 6,
    minWidth: 80,
  },
  buttonText: {
    color: 'white',
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

export default CustomAlertModal;

3. Show Alerts

Using Global Object (Imperative API)

import { GlobalAlert } from '@hexhad/react-native-global-modal';

// Simple alert
GlobalAlert.show({
  title: 'Success!',
  message: 'Your action was completed successfully.',
  type: GlobalAlert.TYPE.SUCCESS,
  buttons: [
    {
      title: 'OK',
      onPress: () => console.log('OK pressed'),
      closeOnPress: true, // Default behavior
    },
  ],
});

// High priority alert (replaces a LOW alert, waits behind other HIGH alerts)
GlobalAlert.show({
  title: 'Critical Error',
  message: 'Something went wrong!',
  priority: GlobalAlert.PRIORITY.HIGH, // High priority
  type: GlobalAlert.TYPE.ERROR,
  buttons: [
    {
      title: 'Retry',
      onPress: () => {
        // Handle retry logic
        console.log('Retrying...');
      },
    },
    {
      title: 'Cancel',
      variant: 'ERROR',
      onPress: () => console.log('Cancelled'),
    },
  ],
});

// Alert with backdrop dismiss
GlobalAlert.show({
  title: 'Info',
  message: 'Tap outside to dismiss',
  backdropDismiss: true,
  buttons: [
    {
      title: 'Got it',
      closeOnPress: true,
    },
  ],
});

// Show multiple alerts in sequence
GlobalAlert.showMultiple([
  {
    title: 'First Alert',
    message: 'This will show first',
    type: GlobalAlert.TYPE.INFO,
    buttons: [{ title: 'Next' }],
  },
  {
    title: 'Second Alert',
    message: 'This will show after the first is closed',
    type: GlobalAlert.TYPE.SUCCESS,
    buttons: [{ title: 'Done' }],
  }
]);

// Auto dismiss after 2 seconds
GlobalAlert.show({
  type: GlobalAlert.TYPE.SUCCESS,
  message: 'Saved!',
  dismissIn: 2000,
});

// Update the alert that is currently on screen
GlobalAlert.show({ type: GlobalAlert.TYPE.LOADING, message: 'Uploading… 0%' });
GlobalAlert.update({ message: 'Uploading… 50%' });

// Inspect the current state
GlobalAlert.isVisible(); // boolean
GlobalAlert.getCurrent(); // AlertData | null

// Hide current alert
GlobalAlert.hide();

// Clear all alerts (including queue)
GlobalAlert.clearAll();

Using React Hook (Declarative API)

import React from 'react';
import { View, Button } from 'react-native';
import { useGlobalAlert } from '@hexhad/react-native-global-modal';

const MyComponent: React.FC = () => {
  const alert = useGlobalAlert();

  const showConfirmation = () => {
    alert.show({
      title: 'Confirm Action',
      message: 'Are you sure you want to proceed?',
      type: alert.TYPE.QUESTION,
      priority: alert.PRIORITY.HIGH, // Ensure this shows immediately
      buttons: [
        {
          title: 'Cancel',
          onPress: () => console.log('Cancelled'),
          closeOnPress: true,
        },
        {
          title: 'Confirm',
          variant: 'SUCCESS',
          onPress: () => {
            console.log('Confirmed!');
            // Handle confirmation logic
          },
          closeOnPress: true,
        },
      ],
    });
  };

  return (
    <View>
      <Button title="Show Confirmation" onPress={showConfirmation} />
    </View>
  );
};

API Reference

GlobalAlertProvider

Main provider component that manages the global alert system.

Props

Prop Type Required Default Description
AlertModal React.ComponentType<AlertModalProps> ✅ - Your custom alert modal component
children React.ReactNode ❌ - Your app content
types Record<string, string> ❌ {} Custom alert types (merged with defaults)
globalAlert GlobalAlertInstance ❌ - Custom global alert instance
ignorePriority boolean ❌ false If true, always show the latest alert immediately

AlertData

Configuration object for alert content and behavior.

type AlertData = {
  type?: string;              // Alert type (ERROR, SUCCESS, etc.)
  variant?: string;           // Visual variant for buttons/styling  
  title?: string;             // Alert title
  message?: string;           // Alert message
  priority?: number;          // Priority: 0 (LOW) or 1 (HIGH)
  backdropDismiss?: boolean;  // Allow dismissing by tapping backdrop
  buttons?: AlertButton[];    // Array of action buttons
  onClose?: () => void;       // Callback when alert closes
  dismissIn?: number;         // Auto-close after this many milliseconds
  [key: string]: any;         // Additional custom properties
};

AlertButton

Configuration for alert buttons.

type AlertButton = {
  title?: string;         // Button text
  variant?: string;       // Visual variant for styling
  onPress?: () => void;   // Button press handler
  closeOnPress?: boolean; // Whether to close alert on press (default: true)
  style?: any;           // Custom button styles
  textStyle?: any;       // Custom button text styles
};

AlertModalProps

Props passed to your custom modal component.

type AlertModalProps = {
  visible: boolean;        // Whether modal should be visible
  data: AlertData | null;  // Alert configuration data
  onClose?: () => void;    // Function to close the alert
  expiresAt?: number | null; // Epoch ms when the alert auto-closes (dismissIn), else null
};

useAlertCountdown Hook

Render a live countdown inside your modal without any timers of your own:

import { useAlertCountdown } from '@hexhad/react-native-global-modal';

const CustomAlertModal = ({ visible, data, onClose, expiresAt }: AlertModalProps) => {
  const seconds = useAlertCountdown(expiresAt); // 0 when there is no deadline
  // ...
  <Text>{seconds > 0 ? `Close (${seconds})` : 'Close'}</Text>
};

useAlertCountdown(expiresAt, intervalMs = 1000) returns the whole seconds left, re-rendering only the component that calls it, once per interval, and only while a deadline exists.

Countdown with "stay" button

GlobalAlert.show({
  title: 'Session expiring',
  message: 'You will be logged out when the countdown ends.',
  priority: GlobalAlert.PRIORITY.HIGH,
  dismissIn: 10000,
  onClose: logout,
  buttons: [
    {
      title: 'Stay signed in',
      closeOnPress: false,
      onPress: () => GlobalAlert.update({ dismissIn: 10000 }), // restart the countdown
    },
    { title: 'Log out' }, // closes → onClose runs
  ],
});

GlobalAlert Object

Properties

  • GlobalAlert.TYPE: Predefined alert types
    • ERROR, WARNING, SUCCESS, INFO, NOTICE, QUESTION, LOADING, TIP
  • GlobalAlert.PRIORITY: Priority levels
    • LOW: 0 (Low priority - default)
    • HIGH: 1 (High priority)

Methods

  • GlobalAlert.show(options: AlertData): Show an alert
  • GlobalAlert.showMultiple(options: AlertData[]): Show multiple alerts in sequence
  • GlobalAlert.hide(): Hide the current alert
  • GlobalAlert.clearAll(): Hide current alert and clear the queue
  • GlobalAlert.update(options: Partial<AlertData>): Merge new values into the alert currently on screen. Pass dismissIn to restart the auto-close timer (0 cancels it); omit it to leave the timer untouched.
  • GlobalAlert.isVisible(): Whether an alert is currently shown
  • GlobalAlert.getCurrent(): The alert currently shown, or null

useGlobalAlert Hook

React hook that provides access to the alert system within components.

const alert = useGlobalAlert();
// Returns: { show, showMultiple, hide, clearAll, update, isVisible, getCurrent, TYPE, PRIORITY }

Note: The hook will throw an error if used outside of GlobalAlertProvider.

Priority System & Queue Management

Only one alert is on screen at a time. What happens to a new alert depends on its priority and on what is currently showing.

Priority Levels

  • High Priority (PRIORITY.HIGH = 1): Never lost. Shows immediately if nothing important is on screen, otherwise waits in line and is shown in arrival order (first in, first out).
  • Low Priority (PRIORITY.LOW = 0): Default. Best effort - shown only when nothing else is on screen or waiting, and silently dropped or replaced otherwise. Use it for toasts and status messages that are fine to miss.

Queue Behavior

With ignorePriority={false} (Default)

Currently showing New alert Result
nothing LOW or HIGH Shows immediately
HIGH HIGH Waits; shown after the current one (and any already waiting) closes
LOW HIGH HIGH shows immediately; the LOW alert is discarded (its onClose is not called)
HIGH (or HIGH alerts waiting) LOW Dropped
LOW LOW The new one replaces it

So show(HIGH 1), show(LOW 1), show(HIGH 2), show(LOW 2) in quick succession shows HIGH 1, then HIGH 2 once it is closed; both LOW alerts are dropped.

With ignorePriority={true}

Every alert waits its turn in a single first-in, first-out queue. Nothing is dropped or replaced.

Queue Processing Details

  • The next alert is shown 50ms after the previous one closes, so the modal can unmount cleanly
  • showMultiple([a, b, c]) shows a under the rules above and queues b and c behind it, in order, regardless of their priority
  • onClose runs at most once per alert, after it has been hidden, so it can safely show another alert
  • Calling the onClose of an alert that is no longer on screen does nothing
  • hide() closes the current alert and continues with the queue; clearAll() also empties it

Examples

Loading Alert with Progress

const upload = async (file: File) => {
  GlobalAlert.show({
    type: GlobalAlert.TYPE.LOADING,
    message: 'Uploading… 0%',
    progress: 0, // custom property, read by your modal
    priority: GlobalAlert.PRIORITY.HIGH,
    // No buttons = user must wait for programmatic dismissal
  });

  await uploadFile(file, (percent) => {
    // Only the modal re-renders; the timer and queue are untouched
    GlobalAlert.update({ message: `Uploading… ${percent}%`, progress: percent });
  });

  // The loading alert is HIGH priority: hide it before showing the LOW
  // result, otherwise the result is dropped while the HIGH alert is up.
  GlobalAlert.hide();
  GlobalAlert.show({
    type: GlobalAlert.TYPE.SUCCESS,
    title: 'Complete!',
    message: 'Upload finished successfully.',
    dismissIn: 2000,
  });
};

Custom Properties & Styling

Your alert modal can access any custom properties you pass:

GlobalAlert.show({
  title: 'Custom Alert',
  message: 'This alert has custom properties',
  customIcon: 'star',           // Custom property
  backgroundColor: '#f0f0f0',   // Custom property
  animationType: 'bounce',      // Custom property
  buttons: [
    {
      title: 'Styled Button',
      style: { 
        backgroundColor: '#FF6B6B', 
        borderRadius: 20,
        paddingHorizontal: 30,
      },
      textStyle: { 
        color: 'white', 
        fontWeight: 'bold',
        fontSize: 16,
      },
      onPress: () => console.log('Custom button pressed'),
    },
  ],
});

Error Handling with Retry

const handleApiError = (error: Error, retryFn: () => void) => {
  GlobalAlert.show({
    title: 'Request Failed',
    message: error.message || 'An unexpected error occurred.',
    type: GlobalAlert.TYPE.ERROR,
    priority: GlobalAlert.PRIORITY.HIGH, // Ensure it shows immediately
    buttons: [
      {
        title: 'Retry',
        variant: 'SUCCESS',
        onPress: () => {
          console.log('Retrying...');
          retryFn();
        },
      },
      {
        title: 'Cancel',
        variant: 'ERROR',
        onPress: () => console.log('Operation cancelled'),
      },
    ],
    onClose: () => {
      console.log('Error alert closed');
    },
  });
};

Confirmation Dialog

const showDeleteConfirmation = (itemName: string, onConfirm: () => void) => {
  GlobalAlert.show({
    title: 'Delete Item',
    message: `Are you sure you want to delete "${itemName}"? This action cannot be undone.`,
    type: GlobalAlert.TYPE.QUESTION,
    priority: GlobalAlert.PRIORITY.HIGH,
    buttons: [
      {
        title: 'Cancel',
        style: { backgroundColor: '#gray' },
        onPress: () => console.log('Delete cancelled'),
      },
      {
        title: 'Delete',
        variant: 'ERROR',
        onPress: () => {
          console.log(`Deleting ${itemName}`);
          onConfirm();
        },
      },
    ],
  });
};

Multiple Alerts Demo

const showMultipleAlertsDemo = () => {
  GlobalAlert.showMultiple([
    {
      title: 'Welcome!',
      message: 'Thank you for using our app',
      type: GlobalAlert.TYPE.SUCCESS,
      buttons: [{ title: 'Next' }],
    },
    {
      title: 'New Features',
      message: 'Check out what\'s new in this version',
      type: GlobalAlert.TYPE.INFO,
      buttons: [{ title: 'Continue' }],
    },
    {
      title: 'Quick Tip',
      message: 'You can customize alerts with your own styling',
      type: GlobalAlert.TYPE.TIP,
      buttons: [{ title: 'Got it!' }],
    },
  ]);
};

Alert Queue Demo

const showQueueDemo = () => {
  // Low priority alert
  GlobalAlert.show({
    title: 'Low Priority 1',
    message: 'This is a low priority alert',
    priority: GlobalAlert.PRIORITY.LOW,
    buttons: [{ title: 'OK' }],
  });
  
  // High priority alert (will interrupt)
  setTimeout(() => {
    GlobalAlert.show({
      title: 'High Priority',
      message: 'This high priority alert interrupts the low priority one',
      priority: GlobalAlert.PRIORITY.HIGH,
      buttons: [{ title: 'Got it' }],
    });
  }, 1000);
  
  // Another high priority (will queue)
  setTimeout(() => {
    GlobalAlert.show({
      title: 'Another High Priority',
      message: 'This will be queued and shown after the first high priority alert',
      priority: GlobalAlert.PRIORITY.HIGH,
      buttons: [{ title: 'Understood' }],
    });
  }, 2000);
};

Advanced Usage

Custom Alert Types

// In your app setup
const customTypes = {
  CUSTOM_SUCCESS: 'CUSTOM_SUCCESS',
  MAINTENANCE: 'MAINTENANCE',
  FEATURE_ANNOUNCEMENT: 'FEATURE_ANNOUNCEMENT',
};

<GlobalAlertProvider 
  AlertModal={CustomAlertModal}
  types={customTypes}
>
  {/* Your app */}
</GlobalAlertProvider>

// Usage
GlobalAlert.show({
  type: 'CUSTOM_SUCCESS', // or GlobalAlert.TYPE.CUSTOM_SUCCESS
  title: 'Feature Updated!',
  message: 'Check out the new functionality.',
});

Using Custom Global Alert Instance

import { createGlobalAlert } from '@hexhad/react-native-global-modal';

const customAlert = createGlobalAlert({
  SPECIAL: 'SPECIAL',
  NOTIFICATION: 'NOTIFICATION',
});

// Use the custom instance
customAlert.show({
  type: customAlert.TYPE.SPECIAL,
  title: 'Special Alert',
  message: 'This uses a custom alert instance',
});

Error Boundaries Integration

class ErrorBoundary extends React.Component {
  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    GlobalAlert.show({
      title: 'Application Error',
      message: 'Something went wrong. The app will reload.',
      type: GlobalAlert.TYPE.ERROR,
      priority: GlobalAlert.PRIORITY.HIGH,
      buttons: [
        {
          title: 'Reload App',
          onPress: () => {
            // Reload or restart logic
            window.location.reload();
          },
        },
      ],
    });
  }
  
  render() {
    return this.props.children;
  }
}

TypeScript Support

The library is fully typed with comprehensive TypeScript definitions:

import type { 
  AlertData, 
  AlertButton, 
  AlertModalProps,
  AlertModalRef,
  GlobalAlertInstance,
  GlobalAlertProviderProps,
  Priority
} from '@hexhad/react-native-global-modal';

// Example: Typed custom alert function
const showTypedAlert = (config: AlertData): void => {
  GlobalAlert.show({
    ...config,
    priority: config.priority ?? GlobalAlert.PRIORITY.LOW, // Default to low priority
  });
};

Best Practices

  1. Use High Priority Sparingly - Reserve PRIORITY.HIGH for critical alerts that must interrupt the user
  2. Provide Clear Actions - Always include actionable buttons unless the alert is purely informational
  3. Handle onClose Properly - Use onClose callback for cleanup when alerts are dismissed
  4. Custom Properties - Leverage custom properties to pass additional data to your modal component
  5. Error Handling - Always handle button press errors gracefully
  6. Queue Management - Consider using ignorePriority={true} for simpler queue behavior if priority handling isn't needed
  7. Backdrop Dismiss - Use backdropDismiss for non-critical alerts to improve UX
  8. Multiple Alerts - Use showMultiple() for onboarding flows or sequential information
  9. Button Variants - Use consistent button variants across your app for better UX

Troubleshooting

Common Issues

  1. "GlobalAlert.show called before GlobalAlertProvider mounted"

    • Ensure GlobalAlertProvider wraps your app at the root level
    • Don't call GlobalAlert.show() during app initialization before the provider mounts
  2. "useGlobalAlert must be used within a GlobalAlertProvider"

    • The useGlobalAlert() hook can only be used inside components wrapped by GlobalAlertProvider
  3. Alerts not showing

    • Check that your AlertModal component properly handles the visible prop
    • Ensure your modal component renders when data is not null
  4. Queue not working as expected

    • Review the priority system documentation
    • Consider using ignorePriority={true} for simpler behavior
  5. Backdrop dismiss not working

    • Ensure your modal handles onRequestClose and touch events on the backdrop
    • Check that backdropDismiss is set to true in your alert data

Performance & What Changed in 0.4

Version 0.4 is a rewrite of the queue core. The public API is unchanged and purely additive, but the internals moved out of React state into a small external store that only the modal host subscribes to (useSyncExternalStore). Measured in Jest against 0.3.x with the same harness:

Metric 0.3.x 0.4
Modal re-renders when the app tree re-renders 20x (navigation, theme, store updates) 20 0
Modal renders per show → auto-close cycle 2 2
setTimeouts created per dismissIn alert 2 (duplicate) 1
Renders for 10 rapid show() calls in one tick 1 1

What that means in practice:

  • Your AlertModal no longer re-renders with the rest of your app. Previously it re-rendered on every render of whatever wrapped the provider; now only when an alert actually changes.
  • No duplicate or leaked timers. One timer per timed alert; the 50ms "show next" timer is cancelled and collapsed instead of re-scheduled on every close.
  • One code path for show/queue instead of three copies, covered by 24 unit tests.

Bugs fixed on the way (each had a failing test against 0.3.x):

  • useGlobalAlert() always threw — the provider never supplied the context.
  • The types and globalAlert provider props were ignored.
  • onClose could fire twice (e.g. a default OK button whose onPress is onClose and that also closes via closeOnPress).
  • A stale onClose from a replaced alert could close the newer alert.
  • Showing an alert from inside onClose hid it immediately.
  • showMultiple showed only the last LOW alert instead of the whole sequence.
  • Alerts shown from a child's mount effect hit "provider not mounted".
  • Toggling ignorePriority wiped the queue.

Trade-offs to be aware of:

  • Requires React 18+ (React Native 0.69+) for useSyncExternalStore.
  • The queue semantics changed on purpose — see the migration guide below.

Migrating from 0.3.x

Nothing is removed. Existing GlobalAlert.show / hide / clearAll / showMultiple calls, GlobalAlertProvider props and AlertModal components keep compiling and running. Three behaviours changed, and three new props/methods are worth adopting.

1. Queue behaviour (behaviour change)

Situation 0.3.x 0.4
HIGH on screen, new HIGH arrives New one shows immediately; old one re-queued New one waits; shown after the current closes
Queue order LIFO (most recent first) FIFO (arrival order)
HIGH on screen (or waiting), new LOW arrives LOW shows immediately; HIGH re-queued and reappears later LOW is dropped
LOW on screen, new HIGH arrives HIGH shows; LOW discarded same
LOW on screen, new LOW arrives newest replaces same
ignorePriority={true} newest always interrupts, LIFO single FIFO queue, nothing dropped
showMultiple([a, b, c]) effectively only c for LOW items a, then b, then c

What to check in your app:

  • Anything the user must see or answer must be PRIORITY.HIGH. A LOW alert fired while a HIGH one is up (an API error, say) is now dropped instead of jumping in front.

  • Replacing a HIGH alert with another (loading → result) needs an explicit hide() first, because a new HIGH no longer interrupts:

    GlobalAlert.show({ type: 'LOADING', priority: GlobalAlert.PRIORITY.HIGH, message: 'Saving…' });
    await save();
    GlobalAlert.hide();                       // ← new in 0.4
    GlobalAlert.show({ type: 'SUCCESS', message: 'Saved', dismissIn: 2000 });
  • If you relied on a HIGH alert coming back after a LOW toast closed, that no longer happens (the toast is dropped instead). Make the toast HIGH if it must show afterwards.

  • If you depended on showMultiple showing only the last item, pass just that item.

2. onClose is called exactly once, after hiding

Modal code that worked around double onClose calls (guards, closed flags) can be removed. onClose is now safe to call from a button's onPress and again via closeOnPress; the second call is a no-op.

3. React 18+

Bump React if you are below 18. There is no other install step.

New things worth adopting

  • expiresAt prop on your modal + useAlertCountdown(expiresAt) for "Close (5)" buttons.
  • GlobalAlert.update(partial) to change the alert on screen (progress, messages) without re-showing it; pass dismissIn to restart the auto-close timer.
  • GlobalAlert.isVisible() / getCurrent() for async code that needs to know whether an alert is up.
  • useGlobalAlert() now works, and its TYPE includes the provider's custom types.

Contributing

See the contributing guide to learn how to contribute to the repository and the development workflow.

License

MIT


Made with ❤️ for the React Native community

About

A custom-built component that replicates the functionality of the React Native Alert, providing the same behavior with additional styling and customization options.

Resources

Code of conduct

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages