1.0.3 β’ Published 5 months ago
@aniruddha1806/toast v1.0.3
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/toastFeatures
- π― 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
| Prop | Type | Default | Description |
|---|---|---|---|
id | string | auto-generated | Unique identifier for the toast |
message | string | undefined | Main toast message |
title | string | undefined | Toast title (optional) |
description | string | undefined | Additional description text |
status | ToastStatus | "default" | Toast type/status |
duration | number | 5000 | Auto-dismiss duration in ms (0 = no auto-dismiss) |
position | ToastPosition | "bottom-right" | Toast position on screen |
pauseOnHover | boolean | false | Pause timer when hovering |
role | ToastRole | "status" | ARIA role for accessibility |
onClose | () => void | undefined | Callback when toast is closed |
className | string | undefined | Custom CSS class |
showProgressBar | boolean | true | Show 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 };
};