enoviq-react-toast-message
Version:
A comprehensive React toast message library providing alerts, popups, confirmations, and toast notifications with customizable styling and behavior.
521 lines (402 loc) ⢠14.3 kB
Markdown
A comprehensive React toast message library providing various notification components including alerts, popups, confirmations, and toast messages with customizable styling and behavior.
```bash
npm install enoviq-react-toast-message
```
or
```bash
yarn add enoviq-react-toast-message
```
- šÆ **Multiple Component Types**: Alert popups, message popups, toast notifications, and confirmation dialogs
- šØ **Customizable Styling**: Support for different types (error, warning, success, info)
- š **Flexible Positioning**: 6 position options (TopLeft, TopCenter, TopRight, BottomLeft, BottomCenter, BottomRight)
- š§ **Easy Integration**: Simple API with React hooks support
- š± **Responsive Design**: Works across different screen sizes
- ā” **Lightweight**: Minimal dependencies
- š **Event Handling**: Custom button click handlers and callbacks
- ā±ļø **Auto-dismiss**: Configurable duration with hover-to-pause functionality
- š **Modern Toast System**: Advanced toast manager with stacking and positioning
## Components
### Available Components
- `ToastMessage` - Modern toast notification with progress bar and positioning
- `ToastContainer` - Container component for managing multiple toasts
- `toast` - Toast manager utility for programmatic control
- `EnvAlertPopupBox` - Alert popup with customizable message and type
- `EnvMsgPopUp` - Message popup with title, subtitle, and message
- `EnvToast` - Legacy toast notification with auto-dismiss functionality
- `EnvShowConfirm` - Confirmation dialog with promise-based response
## Usage
### Modern Toast System (Recommended)
#### Basic Setup
First, add the ToastContainer to your app root:
```javascript
import React from 'react';
import { ToastContainer, toast } from 'enoviq-react-toast-message';
function App() {
return (
<div className="App">
{/* Your app content */}
<button onClick={() => toast.success("Hello World!")}>
Show Toast
</button>
{/* Add ToastContainer at the end */}
<ToastContainer />
</div>
);
}
export default App;
```
```javascript
import { toast } from 'enoviq-react-toast-message';
// Basic usage
toast.success("Operation completed successfully!");
toast.error("Something went wrong!");
toast.warning("Please check your input!");
toast.info("Here's some information");
// With position options
toast.success("Success message", { position: "TopCenter" });
toast.error("Error message", { position: "BottomLeft" });
toast.warning("Warning message", { position: "BottomRight" });
// With custom duration (milliseconds)
toast.info("This stays for 5 seconds", { duration: 5000 });
toast.warning("This stays until manually closed", { duration: 0 });
// Manual removal
const toastId = toast.info("Click to close");
// Later...
toast.remove(toastId);
// Clear all toasts
toast.clear();
```
- `"TopLeft"` - Top left corner
- `"TopCenter"` - Top center
- `"TopRight"` - Top right corner (default)
- `"BottomLeft"` - Bottom left corner
- `"BottomCenter"` - Bottom center
- `"BottomRight"` - Bottom right corner
#### Complete Modern Example
```javascript
import React from 'react';
import { ToastContainer, toast } from 'enoviq-react-toast-message';
function App() {
const showAllToasts = () => {
toast.success("Success! Operation completed.", { position: "TopRight" });
toast.error("Error! Something went wrong.", { position: "TopLeft" });
toast.warning("Warning! Check your input.", { position: "BottomCenter" });
toast.info("Info! Here's some information.", { position: "BottomRight" });
};
const showPersistentToast = () => {
toast.warning("This toast stays until you close it!", {
duration: 0,
position: "TopCenter"
});
};
const showTimedToast = () => {
toast.info("This disappears in 10 seconds", {
duration: 10000,
position: "BottomLeft"
});
};
return (
<div className="App">
<h1>Modern Toast System Demo</h1>
<div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
<button onClick={showAllToasts}>Show All Types</button>
<button onClick={() => toast.success("Success!", { position: "TopCenter" })}>
Success Toast
</button>
<button onClick={() => toast.error("Error!", { position: "BottomLeft" })}>
Error Toast
</button>
<button onClick={() => toast.warning("Warning!", { position: "BottomCenter" })}>
Warning Toast
</button>
<button onClick={() => toast.info("Info!", { position: "TopLeft" })}>
Info Toast
</button>
<button onClick={showPersistentToast}>Persistent Toast</button>
<button onClick={showTimedToast}>10s Duration</button>
<button onClick={() => toast.clear()}>Clear All</button>
</div>
<ToastContainer />
</div>
);
}
export default App;
```
Display a message popup with title, subtitle, and message.
```javascript
<EnvMsgPopUp
title="Title"
subtitle="Subtitle"
message="Your message here"
onBtnClick={handleClose}
/>
```
**Props:**
- `title` (string) - Main title of the popup
- `subtitle` (string) - Subtitle text
- `message` (string) - Main message content
- `onBtnClick` (function) - Callback function when button is clicked
Display an alert popup with different severity types.
```javascript
<EnvAlertPopupBox msg="Alert message" type="error" onBtnClick={handleClose} />
```
**Props:**
- `msg` (string) - Alert message content
- `type` (string) - Alert type: `"error"`, `"warning"`, `"success"`, `"info"`
- `onBtnClick` (function) - Callback function when button is clicked
Display a toast notification with auto-dismiss functionality.
```javascript
<EnvToast msg="Toast message" type="warning" onBtnClick={handleClose} />
```
**Props:**
- `msg` (string) - Toast message content
- `type` (string) - Toast type: `"error"`, `"warning"`, `"success"`, `"info"`
- `onBtnClick` (function) - Callback function when closed
Display a confirmation dialog and get user response.
```javascript
const handleConfirm = async () => {
const result = await EnvShowConfirm({
message: "Are you sure you want to delete this item?",
});
if (result) {
// User confirmed
console.log("User confirmed the action");
} else {
// User cancelled
console.log("User cancelled the action");
}
};
```
**Parameters:**
- `message` (string) - Confirmation message to display
**Returns:**
- Promise that resolves to `true` if confirmed, `false` if cancelled
All components support the following type options for different styling:
- `"success"` - Green color scheme for success messages
- `"error"` - Red color scheme for error messages
- `"warning"` - Orange/yellow color scheme for warnings
- `"info"` - Blue color scheme for informational messages
```javascript
import { useState, useCallback } from "react";
function NotificationManager() {
const [notifications, setNotifications] = useState([]);
const addNotification = useCallback((component) => {
const id = Date.now();
setNotifications((prev) => [...prev, { id, component }]);
}, []);
const removeNotification = useCallback((id) => {
setNotifications((prev) => prev.filter((n) => n.id !== id));
}, []);
const showSuccess = (message) => {
addNotification(
<EnvToast
msg={message}
type="success"
onBtnClick={() => removeNotification(id)}
/>
);
};
return (
<div>
<button onClick={() => showSuccess("Operation completed!")}>
Show Success
</button>
<div className="notifications-container">
{notifications.map(({ id, component }) => (
<div key={id}>{component}</div>
))}
</div>
</div>
);
}
```
```javascript
const handleDeleteUser = async (userId) => {
const confirmed = await EnvShowConfirm({
message: `Are you sure you want to delete user ${userId}? This action cannot be undone.`,
});
if (confirmed) {
try {
await deleteUser(userId);
// Show success toast
setPopupMsg(
<EnvToast
msg="User deleted successfully"
type="success"
onBtnClick={() => setPopupMsg("")}
/>
);
} catch (error) {
// Show error alert
setPopupMsg(
<EnvAlertPopupBox
msg="Failed to delete user"
type="error"
onBtnClick={() => setPopupMsg("")}
/>
);
}
}
};
```
This stylesheet defines a centralized set of **CSS variables (custom properties)** for managing fonts, colors, toast/popup themes, and light/dark mode.
It ensures consistent design, easy theming, and maintainability across the app.
---
## š Structure
The CSS variables are organized into these sections:
1. **Font Faces & Variables**
2. **Base Colors & Tokens**
3. **Toast & Popup Variables**
4. **Theme Variants (Light/Dark)**
---
## 1ļøā£ Font Setup
We include multiple custom font weights and provide semantic variable aliases.
```css
:root {
--font-default: "EnoviqFontTypeBlack";
--font-normal: "EnoviqFontTypeBlack";
--font-medium: "EnoviqFontTypeMedium";
--font-bold: "EnoviqFontTypeBold";
--font-light: "EnoviqFontTypeLight";
--font-black-bold: "EnoviqFontTypeBlack";
--font-primary: "Montserrat";
--font-secondary: "Poppins";
}
```
š¹ **Usage Example**
```css
body {
font-family: var(--font-medium), sans-serif;
}
h1 {
font-family: var(--font-bold), sans-serif;
}
```
---
Core color system with semantic roles:
```css
:root {
--primary:
--onPrimary:
--secondary:
--onSecondary:
--background:
--container:
--bs-body-bg:
--bs-body-color:
--bs-primary:
--bs-secondary:
--bs-success:
--bs-info:
--bs-warning:
--bs-danger:
}
```
š¹ **Usage Example**
```css
.button-primary {
background: var(--primary);
color: var(--onPrimary);
}
```
---
Toast notifications and popup dialogs share consistent tokenized styles.
```css
:root {
--enoviq-toast-success-color:
--enoviq-toast-error-color:
--enoviq-toast-warning-color:
--enoviq-toast-info-color:
--enoviq-toast-background:
--enoviq-toast-text-color:
--enoviq-toast-border-radius: 8px;
--enoviq-toast-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
/* Gradient Progress Bars */
--enoviq-toast-success-gradient: linear-gradient(to right,
--enoviq-toast-error-gradient: linear-gradient(to right,
--enoviq-toast-warning-gradient: linear-gradient(to right,
--enoviq-toast-info-gradient: linear-gradient(to right,
}
```
```css
:root {
--enoviq-popup-success-gradient: linear-gradient(135deg, var(--enoviq-toast-success-color),
--enoviq-popup-error-gradient: linear-gradient(135deg, var(--enoviq-toast-error-color),
--enoviq-popup-warning-gradient: linear-gradient(135deg, var(--enoviq-toast-warning-color),
--enoviq-popup-info-gradient: linear-gradient(135deg, var(--enoviq-toast-info-color),
--enoviq-popup-close-color:
--enoviq-popup-shadow: 0 25px 50px rgba(0, 0, 0, 0.2);
}
```
š¹ **Usage Example**
```css
.toast-success {
background: var(--enoviq-toast-background);
border-left: 5px solid var(--enoviq-toast-success-color);
}
.popupIcon.success {
background: var(--enoviq-popup-success-gradient);
}
```
---
We support both **light** and **dark** themes via `data-bs-theme` attribute.
```css
:root[data-bs-theme="light"] {
--bs-body-bg:
--bs-body-color:
--enoviq-toast-background:
--enoviq-toast-text-color:
--enoviq-toast-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}
```
```css
:root[data-bs-theme="dark"] {
--bs-body-bg:
--bs-body-color:
--enoviq-toast-background:
--enoviq-toast-text-color:
--enoviq-toast-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
}
```
š¹ **Usage Example**
```html
<html data-bs-theme="dark"> <!-- Switch theme dynamically -->
```
---
- Add new semantic tokens (e.g., `--success-bg`, `--error-bg`) to unify button, toast, and popup styling.
- Override per-component if needed, while keeping fallback to global variables.
---
## ā
Summary
- **Fonts**: Centralized via custom faces & variables.
- **Colors**: Semantic tokens for primary, secondary, success, warning, error.
- **Toasts & Popups**: Reusable tokens with gradients, shadows, and borders.
- **Themes**: Automatic light/dark mode support via `[data-bs-theme]`.
---
## Best Practices
1. **State Management**: Use React state to manage which popup/toast is currently displayed
2. **Event Handling**: Always use `event.preventDefault()` in button handlers to prevent form submission
3. **Async Operations**: Use the confirmation component with async/await for better user experience
4. **Type Consistency**: Use appropriate types (`error`, `warning`, `success`, `info`) for semantic meaning
5. **Cleanup**: Always provide proper close handlers to prevent memory leaks