🚀 Big News: Socket Acquires Coana to Bring Reachability Analysis to Every Appsec Team.Learn more
Socket
DemoInstallSign in
Socket

react-native-alertify

Package Overview
Dependencies
Maintainers
1
Versions
14
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-native-alertify

React Native Alertify is a library that provides a simple and customizable alert component for React Native applications

1.0.4
latest
Source
npm
Version published
Weekly downloads
0
Maintainers
1
Weekly downloads
 
Created
Source

React Native Alertify

React Native Alertify is a library that provides a simple and customizable alert component for React Native applications.

Features

  • Flexible Alert Configuration: Customize the appearance and behavior of alerts by leveraging a wide range of configuration options.
  • Title and Message: Display informative titles and descriptive messages to provide context within the alerts.
  • Alert Types: Choose from various pre-defined alert types, including success, error, info, and warning, to convey different levels of urgency or importance.
  • Duration Control: Set the duration for which alerts will be displayed before automatically closing, ensuring optimal visibility and user experience.
  • Indicator Options: Choose between different types of indicators, such as icons or progress bars, to visually enhance the alerts.
  • Custom Icons: Add custom icon components or elements to further enhance the visual representation of alerts.
  • Interaction Callbacks: Attach callback functions to handle user interactions, such as pressing or interacting with alerts.
  • Stay Open Option: Configure alerts to stay open until explicitly closed by the user, allowing extended visibility for critical information.
  • Dismissible Alerts: Enable alerts to be dismissed when pressed, providing users with control over their display.
  • Shadow Customization: Customize the shadow color and other properties of alerts to match your application's design language.
  • Progress Bar: Show a progress bar within alerts to indicate ongoing processes or tasks.
  • Loading Indicator: Display a loading indicator within alerts to indicate activity or loading states.
  • Animation Modes: Choose between different animation modes for the loading indicator, allowing for unique visual effects.
  • Swipable Alerts: Enable swiping gestures to dismiss alerts, offering intuitive and convenient user interaction.
  • Background Customization: Customize the alert background to match the alert type color or your preferred color scheme.
  • Hide After Loading: Automatically hide alerts after completion of loading, streamlining the user experience.
  • Responsive Design: Ensure optimal rendering across different devices.
  • React Native Safe Area Support: Seamlessly integrate with the react-native-safe-area-context library to handle safe areas in your app, ensuring proper rendering across different devices.

These features provide extensive customization options and enhance the engagement and usability of react-native-alertify, making it a powerful and versatile library for creating interactive and visually appealing alerts in your React Native applications.

Demo

See the demo here, the gif looks a bit laggy but the library is smooth is only a mistake when converting the gif.

Installation

You can install React Native Alertify using either Yarn or npm.

yarn add react-native-alertify

or

npm install react-native-alertify

Usage

This library, react-native-alertify, makes use of the react-native-safe-area-context library, which provides functionality for handling safe areas in React Native applications. We would like to acknowledge and give credit to the creators of react-native-safe-area-context for their valuable contribution to the React Native ecosystem.

If you find react-native-safe-area-context useful, we encourage you to visit the official documentation of react-native-safe-area-context to learn more about its features and usage. The creators have put in significant effort to develop and maintain this library, and your support and recognition are greatly appreciated.

If you dont have react-native-safe-area-context installed in your project, you can install it using either Yarn or npm.

yarn add react-native-safe-area-context

or

npm install react-native-safe-area-context

AlertProvider

To use React Native Alertify, you need to wrap your app with the AlertProvider component, ensure that the react-native-safe-area-context library is installed, and that the SafeAreaProvider component wrap the AlertProvider component to work properly.

import { AlertProvider } from 'react-native-alertify';
import { SafeAreaProvider } from 'react-native-safe-area-context';

const App = () => {
  return (
    <SafeAreaProvider>
      <AlertProvider>
        {/* Your app content here */}
      </AlertProvider>
    </SafeAreaProvider>
  );
};

Props of AlertProvider

The AlertProvider component accepts the following props:

NameDefault ValueDescription
children-The children components to be wrapped by the AlertProvider.
themeDefaultThemeThe theme to be used by the AlertProvider.
useDeviceThemefalseSet to true if the AlertProvider should take the theme from the device.
preferredAppearance'light'Set the preferred appearance of the AlertProvider.
commonConfigAlertCommonPropsThe common configuration to be used by the AlertProvider. This configuration will be used by all alerts, unless the alert has its own configuration.

After wrapping your app with AlertProvider, you can use the alert by accessing the context using the useAlertContext hook.

Alert Context

import { useAlertContext } from 'react-native-alertify';

const MyComponent = () => {
  const { showAlert, onClose, onOpen, isShowing } = useAlertContext();

  return (
    {/* Your app content here */}
  );
};

Props of AlertContext

The useAlertContext hook provides the following props:

NameDescription
showAlertDisplays an alert with the specified properties.
onCloseUse this function if you want to perform an action when the alert's state changes to closed.
onOpenUse this function if you want to perform an action when the alert's state changes to open.
changeContentUse this function if you want to change the content of the alert.
isLoadingReturns the current state of the loader.
isShowingReturns the current state of the alert.

If you want to see more information and examples about each of these props, please refer to the API Methods section.

Customization

The AlertProvider component allows users to customize the theme by providing a custom theme object of type AlertTheme.

AlertThemeProps

The AlertThemeProps object consists of the following properties:

NameTypeDescription
colorsAlertThemeColorsColor values for different elements in the alert.
fontSizesAlertThemeFontSizesFont-related properties for the alert.

AlertThemeColors

The AlertThemeColors object defines color values for various parts of the alert:

NameTypeDescription
lightAlertThemeColorSetColors for the light theme.
darkAlertThemeColorSetColors for the dark theme.

AlertThemeColorSet

The AlertThemeColorSet object defines color values for a specific theme (light or dark):

NameTypeDescription
backgroundColorstringBackground color of the alert.
successstringColor for success-themed alerts.
errorstringColor for error-themed alerts.
infostringColor for info-themed alerts.
warningstringColor for warning-themed alerts.
titleColorstringColor for the title text.
messageColorstringColor for the message text.
shadowAlertThemeShadowShadow configuration for the alert.
loadingIconColorstringColor for the loading icon.

AlertThemeFontSizes

The AlertThemeFontSizes object specifies font-related properties for the alert:

NameTypeDescription
fontSizeTitlenumberFont size for the title text.
fontSizeMessagenumberFont size for the message text.
fontFamilystringFont family to be used in the alert.

AlertThemeShadow

The AlertThemeShadow object defines properties related to the shadow effect of the alert:

NameTypeDescription
shadowColorstringColor of the shadow.
shadowOpacitynumberOpacity of the shadow.
shadowOffset{ width: number, height: number }Offset of the shadow.
shadowRadiusnumberRadius of the shadow.
elevationnumberElevation value for the shadow (Android specific).

By providing a custom theme object that conforms to the AlertTheme interface, users can customize the colors, font sizes, and other visual aspects of the alert component to match their application's design and branding.

Customization Example

To customize the theme of the AlertProvider, you can provide a custom theme object of type AlertTheme. Here's an example of how you can define a custom theme:

import { AlertProvider, AlertTheme } from 'react-native-alertify';

const customTheme: AlertTheme = {
  colors: {
    light: {
      backgroundColor: '#F5F5F5',
      success: '#008000',
      error: '#FF0000',
      info: '#0000FF',
      warning: '#FFA500',
      titleColor: '#333333',
      messageColor: '#666666',
      shadow: {
        shadowColor: '#000000',
        shadowOpacity: 0.3,
        shadowOffset: {
          width: 2,
          height: 2,
        },
        shadowRadius: 4,
        elevation: 4,
      },
      loadingIconColor: '#555555',
    },
    dark: {
      backgroundColor: '#222222',
      success: '#00FF00',
      error: '#FF0000',
      info: '#FFFFFF',
      warning: '#FFA500',
      titleColor: '#FFFFFF',
      messageColor: '#CCCCCC',
      shadow: {
        shadowColor: '#000000',
        shadowOpacity: 0.5,
        shadowOffset: {
          width: 3,
          height: 3,
        },
        shadowRadius: 6,
        elevation: 6,
      },
      loadingIconColor: '#CCCCCC',
    },
  },
  fontSizes: {
    fontSizeTitle: 18,
    fontSizeMessage: 14,
    fontFamily: 'Roboto',
  },
};

const App = () => {
  return (
    <AlertProvider theme={customTheme}>
      {/* Your app components */}
    </AlertProvider>
  );
};

export default App;

In this example, we define a custom theme object customTheme with color values and font-related properties for both the light and dark themes. You can adjust the color values, font sizes, and other properties according to your preferences. Then, you can wrap your app components with the AlertProvider component and provide the theme prop with your custom theme object.

By using a custom theme, you can ensure that the alerts rendered by react-native-alertify align with your application's design and branding.

API Methods

showAlert

The showAlert method displays an alert with the specified properties.

Example

import { useAlertContext } from 'react-native-alertify';

const MyComponent = () => {
  const { showAlert } = useAlertContext();

  const handleButtonPress = () => {
    showAlert({
      title: 'Hello',
      message: 'Welcome to React Native Alertify!',
      type: 'success',
      duration: 3000,
    });
  };

  return (
    <Button title="Show Alert" onPress={handleButtonPress} />
  );
};

ShowAlert Props

NameDefault ValueTypeDescription
title-stringThe title of the alert.
message-stringThe message content of the alert.
type'success'string | AlertTypeThe type of the alert, such as success, error, info, or warning.
duration3000msnumberThe duration (in milliseconds) for which the alert will be displayed.
indicatorType'icon'string | AlertIndicatorTypeThe type of indicator to display with the alert, such as an icon or a bar.
iconnullReactNodeThe custom icon component or element to display with the alert.
showIndicatortruebooleanSpecifies whether to display the indicator (icon or bar) with the alert.
onPressnullfunctionA callback function to be called when the alert is pressed or interacted with.
stayOpenfalsebooleanSpecifies if the alert should stay open until the user closes it.
dismissiblefalsebooleanSpecifies if the alert should hide when pressed.
shadowColorByTypefalsebooleanSpecifies if the shadow color should be the same as the alert type color.
showProgressfalsebooleanSpecifies if the alert should show a progress bar.
progressColor-stringSpecifies the color of the progress bar. If not provided, it takes the color of the alert type.
isLoadingfalsebooleanSpecifies if the alert should show a loading indicator.
loadingAnimationMode'normal''normal' | 'divided'Specifies the animation mode of the loading indicator.
swipeablefalsebooleanSpecifies if the alert should be swipeable.
backgroundAsTypefalsebooleanSpecifies if the background color should be the same as the alert type color.
hideAfterLoadingtruebooleanSpecifies if the alert should hide after loading.

changeContent

The changeContent method allows you to change the content of the alert.

Example

const {showAlert, isShowing, setLoader, isLoading, changeContent} =
  useAlertContext();
const simulateAsync = (number: number) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      number > 0.5 ? resolve(true) : reject();
    }, 2000);
  });
};

const handleClick = async () => {
  const random = Math.random();
  setLoader(true);
  showAlert({
    title: 'Loading',
    message: 'Please wait...',
  });
  try {
    await simulateAsync(random);
    setLoader(false);
    changeContent({
      title: 'Success',
      message: 'You have successfully loaded the alert',
      type: 'success',
    });
  } catch (e) {
    setLoader(false);
    changeContent({
      title: 'Error',
      message: 'Something went wrong',
      type: 'error',
    });
  }
};

Props

The changeContent method accepts the same props as the showAlert method, see the ShowAlert Props section for more details.

setLoader

The setLoader method allows you to handle the loading state of the alert.

Example

const {showAlert, isShowing, setLoader, isLoading} = useAlertContext();
const simulateAsync = (number: number) => {
  setLoader(true);
  showAlert({
    title: 'Loading',
    message: 'Please wait...',
  });
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      number > 0.5 ? resolve(true) : reject();
    }, 2000);
  });
  setLoader(false);
};

React.useEffect(() => {
  const random = Math.random();
  simulateAsync(random);
}, []);

Props

NameDefault ValueTypeDescription
valuefalsebooleanSpecifies if the alert should show a loading indicator.

onClose

Note: The onClose method is under development and may cause problems. Use it with caution.

The onClose method allows you to register a callback function to be called when the alert's state changes to closed.

onClose(callback: () => void): void;

Use this function if you want to perform certain actions when the alert's state changes to closed.

Example:

onClose(() => {
  // Your code here
});

onOpen

Note: The onOpen method is under development and may cause problems. Use it with caution.

The onOpen method allows you to register a callback function to be called when the alert's state changes to open.

onOpen(callback: () => void): void;

Use this function if you want to perform certain actions when the alert's state changes to open.

Example:

onOpen(() => {
  // Your code here
});

isShowing

The isShowing property returns the current state of the alert.

isShowing: boolean;

You can use this property to check if the alert is currently being displayed.

if (isShowing) {
  // Alert is showing
} else {
  // Alert is not showing
}

isLoading

The isLoading property returns the current loading state of the alert.

isLoading: boolean;

You can use this property to check if the alert is currently loading.

if (isLoading) {
  // Alert is loading
} else {
  // Alert is not loading
}

Please note that the onClose and onOpen methods are still under development and may have limitations or issues. Use them with caution and make sure to test thoroughly in your application.

Troubleshooting

iOS App Build Issues

If you have cloned the repository and are experiencing difficulties starting the iOS app, it may be due to a conflict with the derived data folder in Xcode. To resolve this issue, follow the steps below:

  • Open the apps/example-app/ios/Example-App.xcworkspace file in Xcode.

  • Click on the File menu in the top-left corner of Xcode.

  • From the dropdown menu, select Workspace Settings.

  • In the Derived Data section, click on the path where the derived data is located.

  • Remove the derived data folder by either deleting it or moving it to a different location.

  • After removing the derived data folder, try running the iOS app again. You can run the app by executing the following command inside the apps/example-app directory:

    react-native run-ios
    

    Alternatively, you can run the command in the root directory of the project:

    npx nx serve example-app:run-ios
    

If you find any issues with the library, please create an issue, specifying the problem and how to reproduce it, if is possible upload a screenshot or video of the issue.

I'll try to fix it as soon as possible.

Certainly! Here's an example of a "Contributing" section for your README:

Contributing

Thank you for considering contributing to the React Native Alertify library! We welcome any contributions that help improve the library and provide a better experience for users. To contribute, please follow these guidelines:

  • Fork the React Native Alertify repository on GitHub.
  • Clone your forked repository to your local machine.
  • Create a new branch for your feature or bug fix: git checkout -b feature/your-feature or git checkout -b bugfix/your-bug-fix.
  • Make your changes and ensure that the code follows the project's coding conventions.
  • Commit your changes with descriptive commit messages.
  • Push your branch to your forked repository: git push origin feature/your-feature.
  • Create a pull request from your forked repository to the main repository's main branch.
  • Provide a clear and detailed explanation of your changes in the pull request description.
  • Be responsive to any feedback or requests for changes from the maintainers.

We appreciate your contributions and will review the pull request as soon as possible. Together, let's make React Native Alertify even better!

Creator

This library was created by Esteban Estrada, a passionate developer who loves to learn new technologies and build cool things.

Esteban Estrada

Esteban Estrada is an experienced full stack developer. He is passionate about creating efficient and user-friendly solutions for developers. This library, react-native-alertify, is one of his contributions to the React Native community.

You can connect with Esteban Estrada on LinkedIn and GitHub to learn more about his work and other projects.

Feel free to reach out to Esteban Estrada with any questions, feedback, or suggestions related to react-native-alertify.

License

This library is open-source and available under the MIT License. You are free to use, modify, and distribute this library for personal or commercial purposes. However, it would be greatly appreciated if you provide support to the creator by giving credit and acknowledging their contribution.

Remember to follow the best practices and guidelines while using this library. If you encounter any issues or have suggestions for improvements, feel free to contribute to the repository or reach out to the creator for support.

By using react-native-alertify, you agree to comply with the terms and conditions of the MIT License.

Keywords

react-native

FAQs

Package last updated on 12 Jun 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts