@udhayakiran/toast-message
v1.0.1
Published
A lightweight, customizable toast notification library for JavaScript and React
Maintainers
Readme
Toast Message
A lightweight, customizable toast notification library for JavaScript and React applications. Perfect for displaying temporary messages, alerts, and notifications with beautiful animations and full customization support.
✨ Features
- 🎨 Single Function API - Use
toast.show()for all toast types with full customization - 🎯 Default Colors - Beautiful default colors for each type (success=green, error=red, warning=orange, info=blue)
- 🎨 Custom Colors - Override defaults with custom background and text colors
- ⏸️ Hover Pause - Toast timer automatically pauses when you hover over it
- ⏱️ Custom Duration - Set any duration in milliseconds (0 = never auto-dismiss)
- 📍 6 Position Options - Top/bottom × left/center/right
- ❌ Dismissible - Optional close button for manual dismissal
- ⚛️ React Support - Optional React hooks and components
- 📱 Responsive - Works perfectly on mobile and desktop
- 💪 TypeScript - Full TypeScript support with type definitions
- 🚀 Zero Dependencies - Lightweight with no external dependencies (React is optional peer dependency)
- 🎭 Fully Customizable - Custom styles, classes, and callbacks
📦 Installation
npm install @udhayakiran/toast-message🚀 Quick Start
Vanilla JavaScript
// Import the core bundle (no React dependency)
import { toast } from '@udhayakiran/toast-message/core';
import '@udhayakiran/toast-message/styles.css';
// Show a toast
toast.show('Hello, World!', {
type: 'success',
duration: 3000
});React
import React from 'react';
import { ToastProvider, useToast } from '@udhayakiran/toast-message';
import '@udhayakiran/toast-message/styles.css';
function App() {
return (
<ToastProvider>
<MyComponent />
</ToastProvider>
);
}
function MyComponent() {
const { show } = useToast();
return (
<button onClick={() => show('Success!', { type: 'success' })}>
Show Toast
</button>
);
}📖 Usage
Basic Usage
import { toast } from '@udhayakiran/toast-message/core';
import '@udhayakiran/toast-message/styles.css';
// Simple toast
toast.show('Operation completed!');
// Different types
toast.show('Success!', { type: 'success' });
toast.show('Error occurred!', { type: 'error' });
toast.show('Warning!', { type: 'warning' });
toast.show('Info message', { type: 'info' });Convenience Methods
// Shorthand methods (still available)
toast.success('Operation completed successfully!');
toast.error('Something went wrong!');
toast.warning('Please check your input');
toast.info('Here is some information');Custom Colors
// Custom color overrides default type color
toast.show('Custom purple toast', {
type: 'success', // Type is success but color overrides green
color: '#9333ea', // Custom purple background
textColor: '#fff' // White text
});
// Default colors (used if color not specified):
// Success: #10b981 (green)
// Error: #ef4444 (red)
// Warning: #f59e0b (orange)
// Info: #3b82f6 (blue)Custom Duration
// 10 second duration
toast.show('This will stay for 10 seconds', {
duration: 10000
});
// Never auto-dismiss (stays until manually closed)
toast.show('Important information', {
duration: 0
});Hover Pause
// Toast timer pauses when you hover over it
toast.show('Hover over me to pause!', {
duration: 5000, // 5 seconds, but pauses on hover
type: 'info'
});Custom Position
toast.show('Bottom left toast', {
position: 'bottom-left'
});
// Available positions:
// 'top-left', 'top-center', 'top-right'
// 'bottom-left', 'bottom-center', 'bottom-right'All Options Together
toast.show('Fully customized toast', {
type: 'warning',
color: '#ec4899', // Custom pink (overrides default orange)
textColor: '#fff',
position: 'bottom-right',
duration: 8000, // 8 seconds (pauses on hover)
dismissible: true,
onClose: () => {},
className: 'my-custom-class',
style: { borderRadius: '12px' }
});Remove Toasts
// Remove specific toast by ID
const toastId = toast.show('This will be removed');
toast.remove(toastId);
// Clear all toasts
toast.clear();📚 API Reference
toast.show(message, options?)
Display a toast message. This is the main function for all toast types.
Parameters:
message(string): The message to displayoptions(ToastOptions, optional): Configuration options
Returns: string - Toast ID
toast.success(message, options?)
Display a success toast (shorthand for toast.show(message, { type: 'success', ...options })).
toast.error(message, options?)
Display an error toast (shorthand for toast.show(message, { type: 'error', ...options })).
toast.warning(message, options?)
Display a warning toast (shorthand for toast.show(message, { type: 'warning', ...options })).
toast.info(message, options?)
Display an info toast (shorthand for toast.show(message, { type: 'info', ...options })).
toast.remove(id)
Remove a specific toast by ID.
toast.clear()
Clear all active toasts.
⚙️ ToastOptions
interface ToastOptions {
type?: 'success' | 'error' | 'warning' | 'info';
duration?: number; // Duration in milliseconds (0 = never auto-dismiss)
position?: 'top-left' | 'top-center' | 'top-right' |
'bottom-left' | 'bottom-center' | 'bottom-right';
dismissible?: boolean; // Show close button (default: true)
onClose?: () => void; // Callback when toast is closed
className?: string; // Additional CSS class
style?: CSSProperties; // Inline styles
color?: string; // Custom background color (overrides default type color)
textColor?: string; // Custom text color
}⚛️ React Hooks
useToast()
React hook that provides toast functions and current toast list.
Returns:
{
toasts: Toast[];
show: (message: string, options?: ToastOptions) => string;
success: (message: string, options?: Omit<ToastOptions, 'type'>) => string;
error: (message: string, options?: Omit<ToastOptions, 'type'>) => string;
warning: (message: string, options?: Omit<ToastOptions, 'type'>) => string;
info: (message: string, options?: Omit<ToastOptions, 'type'>) => string;
remove: (id: string) => void;
clear: () => void;
}Example:
import { useToast } from '@udhayakiran/toast-message';
function MyComponent() {
const { show, success, error, toasts } = useToast();
return (
<div>
<button onClick={() => success('Saved!')}>Save</button>
<button onClick={() => error('Failed!')}>Delete</button>
<p>Active toasts: {toasts.length}</p>
</div>
);
}🎨 Styling
The library includes default styles, but you can customize them by:
- Overriding CSS classes - Target the toast classes in your CSS
- Using
classNameoption - Add custom classes to individual toasts - Using
styleoption - Apply inline styles - Using
colorandtextColoroptions - Customize colors per toast
CSS Classes
.toast-container- Main container.toast- Individual toast.toast-success- Success toast variant.toast-error- Error toast variant.toast-warning- Warning toast variant.toast-info- Info toast variant.toast-message- Toast message text.toast-close- Close button
Custom Styling Example
/* Override default styles */
.toast {
border-radius: 12px;
box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
}
/* Custom class */
.my-custom-toast {
font-weight: bold;
font-size: 16px;
}toast.show('Custom styled toast', {
className: 'my-custom-toast',
style: { padding: '20px' }
});📦 Package Exports
The package provides multiple entry points:
Main entry (includes React components):
import { toast, ToastProvider, useToast } from '@udhayakiran/toast-message';Core bundle (vanilla JS, no React):
import { toast } from '@udhayakiran/toast-message/core';Styles:
import '@udhayakiran/toast-message/styles.css';
🌟 Examples
Form Validation
function validateForm(data) {
if (!data.email) {
toast.error('Email is required', { position: 'top-center' });
return false;
}
if (!isValidEmail(data.email)) {
toast.warning('Please enter a valid email', { duration: 5000 });
return false;
}
toast.success('Form submitted successfully!');
return true;
}API Error Handling
async function fetchData() {
try {
const response = await api.get('/data');
toast.success('Data loaded successfully!');
return response.data;
} catch (error) {
toast.error('Failed to load data. Please try again.', {
duration: 0, // Don't auto-dismiss errors
dismissible: true
});
throw error;
}
}Custom Themed Toast
function showCustomNotification(message, theme) {
const themes = {
dark: { color: '#1f2937', textColor: '#fff' },
light: { color: '#f3f4f6', textColor: '#111827' },
purple: { color: '#9333ea', textColor: '#fff' }
};
toast.show(message, {
...themes[theme],
duration: 4000,
position: 'top-center'
});
}🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
📝 License
MIT License - see LICENSE file for details.
🙏 Acknowledgments
Built with ❤️ for the JavaScript and React community.
Made with @udhayakiran/toast-message 🍞
