toastify-react-native

repository·master·Indexed 42 days ago

https://github.com/zahidalidev/toastify-react-native

A highly customizable notification library for React Native (iOS and Android) providing toast messages with support for custom components, icons, and themes. Version 7.2.3 requires react-native-vector-icons. It features a ToastManager for root-level configuration and a Toast API with methods like .success(), .error(), .info(), .warn(), and .show() for granular control over positioning, visibility, and modal behavior.

Tokens
8.1K
Snippets
18
Records
23
Agent score
46%

What's inside toastify-react-native

  1. Understand and use Modal Behavior

    master

    The useModal property determines if a toast uses a modal overlay that blocks interaction with the background screen.

    • useModal: true: The toast appears with an overlay, making the background non-interactive. This ensures visibility over other modals but prevents user interaction with the app content behind the toast.
    • useModal: false: The toast appears without blocking interaction. Users can still interact with the app, but the toast might not appear over other modal components.

    You can set this globally on the ToastManager or per-toast using Toast.show() or the shorthand methods.

    // Global setting via ToastManager
    <ToastManager useModal={true} />
    
    // Per-toast setting via Toast.show()
    Toast.show({
      type: 'success',
      text1: 'Using Modal',
      useModal: true,
    })
    
    // Per-toast setting via shorthand
    Toast.success('Success with Modal!', 'bottom', undefined, undefined, true)
  2. Install toastify-react-native

    master

    Install the package using npm or yarn. Note that this package requires react-native-vector-icons as a dependency. You must follow the official react-native-vector-icons installation guide to complete the setup for your specific platform (iOS/Android).

    npm install toastify-react-native
    # or
    yarn add toastify-react-native
    
    # Required dependency
    npm install react-native-vector-icons
    # or
    yarn add react-native-vector-icons
  3. Upgrade from v6.x to v4.0.0

    master

    When upgrading from version 6.x, be aware of the following breaking changes and improvements:

    • Animation System: Now uses React Native's built-in Modal animations for simplicity.
    • Props: Some props have been removed or renamed for clarity.
    • Styling: The styling system has been improved for better customization.
    • Custom Components: Custom components now receive more props for better control.
  4. Set up ToastManager and show toasts

    master

    To enable notifications in your application, you must include the ToastManager component at the root of your component tree. Once the manager is mounted, you can trigger notifications from anywhere in your app using the Toast object methods (e.g., Toast.success(), Toast.info()).

    import React from 'react'
    import { View, TouchableOpacity, Text } from 'react-native'
    import ToastManager, { Toast } from 'toastify-react-native'
    
    const App = () => {
      const showToasts = () => {
        Toast.success('Promised is resolved')
      }
    
      return (
        <View style={{ flex: 1 }}>
          {/* 1. Add the Manager to your root component */}
          <ToastManager />
          
          {/* 2. Trigger toasts via the Toast object */}
          <TouchableOpacity onPress={showToasts}>
            <Text>SHOW SOME AWESOMENESS!</Text>
          </TouchableOpacity>
        </View>
      )
    }
    
    export default App
  5. Basic Usage of toastify-react-native

    master

    To use the library, you must include the ToastManager component at the root level of your application. Once configured, you can trigger notifications using the Toast object's shorthand methods: Toast.success(), Toast.error(), Toast.info(), and Toast.warn().

    import React from 'react'
    import { View, Button } from 'react-native'
    import ToastManager, { Toast } from 'toastify-react-native'
    
    export default function App() {
      return (
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
          <Button
            title='Show Success Toast'
            onPress={() => {
              Toast.success('Success message!')
            }}
          />
    
          {/* Toast provider should be at the root level */}
          <ToastManager />
        </View>
      )
    }
  6. Create custom toast components

    master

    You can define entirely custom toast layouts by providing a config object to the ToastManager. The config object maps a type string to a component function that receives props like text1, text2, and hide (a function to manually close the toast).

    import React from 'react'
    import { View, Text, StyleSheet } from 'react-native'
    import ToastManager, { Toast } from 'toastify-react-native'
    import Icon from 'react-native-vector-icons/MaterialIcons'
    
    const CustomToast = ({ text1, text2, hide }) => {
      return (
        <View style={styles.customToast}>
          <Icon name='star' size={24} color='#FFD700' />
          <View style={styles.textContainer}>
            <Text style={styles.title}>{text1}</Text>
            {text2 && <Text style={styles.message}>{text2}</Text>}
          </View>
          <Icon name='close' size={20} color='#fff' onPress={hide} />
        </View>
      )
    }
    
    const styles = StyleSheet.create({
      customToast: {
        width: '90%',
        backgroundColor: '#673AB7',
        borderRadius: 10,
        padding: 16,
        flexDirection: 'row',
        alignItems: 'center',
      },
      textContainer: {
        flex: 1,
        marginLeft: 12,
      },
      title: {
        color: '#fff',
        fontWeight: 'bold',
        fontSize: 16,
      },
      message: {
        color: '#fff',
        fontSize: 14,
        marginTop: 4,
      },
    })
    
    export default function App() {
      const toastConfig = {
        custom: (props) => <CustomToast {...props} />,
      }
    
      return (
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
          <Button
            title='Show Custom Toast'
            onPress={() => {
              Toast.show({
                type: 'custom',
                text1: 'Custom Component',
                text2: 'This is a fully custom toast component!',
              })
            }}
          />
    
          <ToastManager config={toastConfig} />
        </View>
      )
    }
  7. Customize icons in Toast.show()

    master

    You can customize icons for individual toasts in several ways:

    1. Change icon name: Pass a different string to the icon property (uses the default icon family).
    2. Change icon family: Pass a different string to iconFamily (e.g., 'FontAwesome').
    3. Use a React component: Pass a custom component to the icon property.
    4. Use JSX directly: Pass a JSX element to the icon property.
    // 1. Different icon name
    Toast.show({
      type: 'success',
      text1: 'Different Icon',
      icon: 'check',
    })
    
    // 2. Different icon family
    Toast.show({
      type: 'error',
      text1: 'FontAwesome Icon',
      icon: 'exclamation-circle',
      iconFamily: 'FontAwesome',
    })
    
    // 3. Custom React component as icon
    const CustomIcon = ({ color }) => (
      <View style={{ width: 30, height: 30, borderRadius: 15, backgroundColor: color || '#4CAF50', alignItems: 'center', justifyContent: 'center' }}>
        <FontAwesome name='check' size={18} color='#FFFFFF' />
      </View>
    )
    
    Toast.show({
      type: 'info',
      text1: 'Custom Component',
      icon: <CustomIcon color='#3498db' />,
    })
    
    // 4. Using JSX directly
    Toast.show({
      type: 'success',
      text1: 'JSX Icon',
      icon: (
        <View style={{ flexDirection: 'row' }}>
          <FontAwesome name='thumbs-up' size={22} color='#4CAF50' />
          <FontAwesome name='thumbs-up' size={22} color='#4CAF50' style={{ marginLeft: -8, marginTop: 5 }} />
        </View>
      ),
    })
  8. Set up the ToastProvider at the root of your app

    master

    To use toastify-react-native, you must include the ToastProvider component at the root level of your application. This component manages the toast lifecycle and accepts an optional config object to override default settings.

    import ToastProvider from 'toastify-react-native';
    
    export default function App() {
      return (
        <ToastProvider 
          config={{
            // Your custom configuration here
          }}
        />
      );
    }
    import ToastProvider from 'toastify-react-native';
    
    export default function App() {
      return (
        <ToastProvider 
          config={{
            // Your custom configuration here
          }}
        />
      );
    }
  9. Configure the ToastManager component

    master

    The ToastManager component is the provider for all toasts in your application. It accepts several props to define the global appearance, positioning, and behavior of toasts. Use these props to set defaults for width, height, theme, animation, and icon styles.

    <ToastManager
      config={toastConfig}
      theme='light'
      position='top'
      icons={{
        success: 'check-circle',
        error: 'error',
        info: 'info',
        warn: 'warning',
        default: 'notifications',
      }}
      iconFamily='MaterialIcons'
      iconSize={24}
    />
  10. Use Toast.show() to display toasts

    master

    Call Toast.show() to trigger a toast notification. You can specify the type, text content, and override global styles or behaviors for individual toast instances.

    Toast.show({
      type: 'success',
      text1: 'Success Message',
      text2: 'This is the secondary text',
      position: 'bottom',
      visibilityTime: 5000,
      autoHide: true,
      onShow: () => console.log('Shown'),
      onHide: () => console.log('Hidden'),
      onPress: () => console.log('Pressed'),
      progressBarColor: '#ff0000',
      backgroundColor: '#000',
      textColor: '#fff',
      icon: 'check',
      iconFamily: 'FontAwesome',
      iconColor: '#fff',
      iconSize: 30,
      theme: 'dark',
      useModal: false,
      closeIcon: 'close-circle',
      closeIconSize: 24,
      closeIconColor: '#fff',
      closeIconFamily: 'Ionicons',
    });
  11. Configure custom toast components via ToastManager

    master

    You can override the default look and feel of specific toast types by passing a config object to the ToastManager. The config object maps toast types (e.g., success) to a render function that receives props (including text1 and text2).

    import React from 'react'
    import { View, Button, Text } from 'react-native'
    import ToastManager, { Toast } from 'toastify-react-native'
    
    // Custom toast configuration
    const toastConfig = {
      success: (props) => (
        <View style={{ backgroundColor: '#4CAF50', padding: 16, borderRadius: 10 }}>
          <Text style={{ color: 'white', fontWeight: 'bold' }}>{props.text1}</Text>
          {props.text2 && <Text style={{ color: 'white' }}>{props.text2}</Text>}
        </View>
      ),
    }
    
    export default function App() {
      return (
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
          <Button
            title='Show Custom Toast'
            onPress={() => {
              Toast.show({
                type: 'success',
                text1: 'Main message',
                text2: 'Secondary message',
                position: 'bottom',
                visibilityTime: 4000,
                autoHide: true,
                onPress: () => console.log('Toast pressed'),
                onShow: () => console.log('Toast shown'),
                onHide: () => console.log('Toast hidden'),
              })
            }}
          />
    
          <ToastManager config={toastConfig} />
        </View>
      )
    }