1.0.3 β€’ Published 5 months ago

@aniruddha1806/toast v1.0.3

Weekly downloads
-
License
MIT
Repository
-
Last release
5 months ago

React Toast Component

A powerful, customizable toast notification system for React applications with TypeScript support. Features multiple toast types, positioning options, progress bars, and advanced timer management.

Installation

npm install @aniruddha1806/toast

Features

  • 🎯 Multiple toast types (success, error, info, warning, default)
  • πŸ“ 6 positioning options (top/bottom + left/center/right)
  • ⏱️ Auto-dismiss with customizable duration
  • πŸ“Š Progress bar with real-time countdown
  • ⏸️ Pause on hover functionality
  • 🎨 Customizable styling and animations
  • πŸ”§ TypeScript support with full type definitions
  • β™Ώ Accessibility features with ARIA support
  • πŸͺ Easy-to-use React hooks
  • 🎭 Built-in icons for all toast types
  • πŸ”„ Advanced timer management with pause/resume

Quick Start

import { ToastProvider, useToast } from '@aniruddha1806/toast';

function App() {
  return (
    <ToastProvider>
      <MyComponent />
    </ToastProvider>
  );
}

function MyComponent() {
  const { successToast, errorToast, infoToast, warningToast } = useToast();

  const handleSuccess = () => {
    successToast('Operation completed successfully!');
  };

  const handleError = () => {
    errorToast('Something went wrong!');
  };

  return (
    <div>
      <button onClick={handleSuccess}>Show Success</button>
      <button onClick={handleError}>Show Error</button>
    </div>
  );
}

Components

ToastProvider

Wrap your application with ToastProvider to enable toast functionality:

import { ToastProvider } from '@aniruddha1806/toast';

function App() {
  return (
    <ToastProvider>
      {/* Your app content */}
    </ToastProvider>
  );
}

useToast Hook

Access toast functionality from any component:

import { useToast } from '@aniruddha1806/toast';

function MyComponent() {
  const { 
    addToast, 
    removeToast, 
    successToast, 
    errorToast, 
    infoToast, 
    warningToast 
  } = useToast();

  // Use the convenience methods or addToast for full control
}

Props & Types

ToastProps

PropTypeDefaultDescription
idstringauto-generatedUnique identifier for the toast
messagestringundefinedMain toast message
titlestringundefinedToast title (optional)
descriptionstringundefinedAdditional description text
statusToastStatus"default"Toast type/status
durationnumber5000Auto-dismiss duration in ms (0 = no auto-dismiss)
positionToastPosition"bottom-right"Toast position on screen
pauseOnHoverbooleanfalsePause timer when hovering
roleToastRole"status"ARIA role for accessibility
onClose() => voidundefinedCallback when toast is closed
classNamestringundefinedCustom CSS class
showProgressBarbooleantrueShow progress bar countdown

Types

type ToastStatus = "success" | "error" | "info" | "warning" | "default";
type ToastPosition = "top-left" | "top-center" | "top-right" | "bottom-left" | "bottom-center" | "bottom-right";
type ToastRole = "alert" | "status" | "log";

Examples

Basic Usage

Simple toast notifications:

import { ToastProvider, useToast } from '@aniruddha1806/toast';

function BasicExample() {
  const { successToast, errorToast, infoToast, warningToast } = useToast();

  return (
    <div style={{ padding: '20px', display: 'flex', gap: '10px' }}>
      <button onClick={() => successToast('Success message!')}>
        Success
      </button>
      <button onClick={() => errorToast('Error message!')}>
        Error
      </button>
      <button onClick={() => infoToast('Info message!')}>
        Info
      </button>
      <button onClick={() => warningToast('Warning message!')}>
        Warning
      </button>
    </div>
  );
}

function App() {
  return (
    <ToastProvider>
      <BasicExample />
    </ToastProvider>
  );
}

Advanced Toast Options

Use the full toast configuration:

import { useToast } from '@aniruddha1806/toast';

function AdvancedExample() {
  const { addToast } = useToast();

  const showAdvancedToast = () => {
    addToast({
      title: 'Upload Complete',
      message: 'Your file has been uploaded successfully.',
      description: 'You can now share the link with others.',
      status: 'success',
      duration: 8000,
      position: 'top-right',
      pauseOnHover: true,
      showProgressBar: true,
      onClose: () => console.log('Toast closed')
    });
  };

  return (
    <button onClick={showAdvancedToast}>
      Show Advanced Toast
    </button>
  );
}

Different Positions

Show toasts in different positions:

import { useToast } from '@aniruddha1806/toast';

function PositionExample() {
  const { addToast } = useToast();

  const positions = [
    'top-left', 'top-center', 'top-right',
    'bottom-left', 'bottom-center', 'bottom-right'
  ];

  return (
    <div style={{ 
      display: 'grid', 
      gridTemplateColumns: 'repeat(3, 1fr)', 
      gap: '10px',
      padding: '20px'
    }}>
      {positions.map(position => (
        <button
          key={position}
          onClick={() => addToast({
            message: `Toast from \${position}`,
            position: position,
            status: 'info'
          })}
        >
          {position}
        </button>
      ))}
    </div>
  );
}

Form Validation Example

Real-world form validation with toasts:

import { useState } from 'react';
import { useToast } from '@aniruddha1806/toast';

function FormExample() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const { successToast, errorToast, warningToast } = useToast();

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    // Validation
    if (!email || !password) {
      warningToast('Please fill in all fields');
      return;
    }

    if (!email.includes('@')) {
      errorToast('Please enter a valid email address');
      return;
    }

    if (password.length < 6) {
      errorToast('Password must be at least 6 characters');
      return;
    }

    setLoading(true);

    try {
      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      successToast({
        title: 'Login Successful',
        message: 'Welcome back!',
        description: 'You have been logged in successfully.',
        duration: 6000
      });
      
      // Reset form
      setEmail('');
      setPassword('');
    } catch (error) {
      errorToast({
        title: 'Login Failed',
        message: 'Invalid credentials',
        description: 'Please check your email and password.',
        duration: 8000
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} style={{ 
      maxWidth: '400px', 
      margin: '0 auto', 
      padding: '20px' 
    }}>
      <div style={{ marginBottom: '16px' }}>
        <label>Email:</label>
        <input
          type="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          style={{ 
            width: '100%', 
            padding: '8px', 
            marginTop: '4px',
            border: '1px solid #ccc',
            borderRadius: '4px'
          }}
        />
      </div>
      
      <div style={{ marginBottom: '16px' }}>
        <label>Password:</label>
        <input
          type="password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          style={{ 
            width: '100%', 
            padding: '8px', 
            marginTop: '4px',
            border: '1px solid #ccc',
            borderRadius: '4px'
          }}
        />
      </div>
      
      <button 
        type="submit" 
        disabled={loading}
        style={{
          width: '100%',
          padding: '12px',
          backgroundColor: loading ? '#ccc' : '#007bff',
          color: 'white',
          border: 'none',
          borderRadius: '4px',
          cursor: loading ? 'not-allowed' : 'pointer'
        }}
      >
        {loading ? 'Logging in...' : 'Login'}
      </button>
    </form>
  );
}

Persistent Toasts

Create toasts that don't auto-dismiss:

import { useToast } from '@aniruddha1806/toast';

function PersistentExample() {
  const { addToast, removeToast } = useToast();

  const showPersistentToast = () => {
    const toastId = addToast({
      title: 'Important Notice',
      message: 'This toast will not auto-dismiss',
      description: 'You must manually close it',
      status: 'warning',
      duration: 0, // 0 means no auto-dismiss
      showProgressBar: false,
      position: 'top-center'
    });

    // Optionally, you can programmatically remove it later
    setTimeout(() => {
      removeToast(toastId);
    }, 10000); // Remove after 10 seconds
  };

  return (
    <button onClick={showPersistentToast}>
      Show Persistent Toast
    </button>
  );
}

TypeScript Usage

The component provides full TypeScript support:

import { useToast, ToastProps, ToastStatus, ToastPosition } from '@aniruddha1806/toast';

interface NotificationService {
  showSuccess: (message: string) => void;
  showError: (message: string) => void;
  showCustom: (config: Partial<ToastProps>) => void;
}

const useNotificationService = (): NotificationService => {
  const { successToast, errorToast, addToast } = useToast();

  const showSuccess = (message: string): void => {
    successToast(message, {
      duration: 4000,
      position: 'top-right' as ToastPosition
    });
  };

  const showError = (message: string): void => {
    errorToast(message, {
      duration: 6000,
      position: 'top-center' as ToastPosition
    });
  };

  const showCustom = (config: Partial<ToastProps>): void => {
    addToast({
      status: 'info' as ToastStatus,
      duration: 5000,
      ...config
    });
  };

  return { showSuccess, showError, showCustom };
};
1.0.3

5 months ago

1.0.2

7 months ago

1.0.1

7 months ago

1.0.0

7 months ago