Skip to content

Alert

A clean, accessible alert component for displaying important messages and notifications. Built with React and styled with Tailwind CSS.

Component Code

import React, { useEffect, useState } from "react";
import {
CheckCircleIcon,
ExclamationTriangleIcon,
InformationCircleIcon,
XCircleIcon,
XMarkIcon,
} from "@heroicons/react/24/outline";
const Alert = ({
type = "info",
title,
message,
duration = 0,
dismissible = true,
onClose,
className = "",
actions,
}) => {
const [isVisible, setIsVisible] = useState(true);
useEffect(() => {
if (duration > 0) {
const timer = setTimeout(() => {
handleClose();
}, duration);
return () => clearTimeout(timer);
}
}, [duration]);
const handleClose = () => {
setIsVisible(false);
if (onClose) {
setTimeout(onClose, 150);
}
};
const getAlertStyles = () => {
const baseStyles =
"flex items-start p-4 rounded-lg border shadow-sm transition-all duration-300";
switch (type) {
case "success":
return `${baseStyles} bg-green-50 border-green-200 text-green-800`;
case "error":
return `${baseStyles} bg-red-50 border-red-200 text-red-800`;
case "warning":
return `${baseStyles} bg-yellow-50 border-yellow-200 text-yellow-800`;
case "info":
default:
return `${baseStyles} bg-blue-50 border-blue-200 text-blue-800`;
}
};
const getIcon = () => {
const iconClass = "w-5 h-5 mt-0.5 flex-shrink-0";
switch (type) {
case "success":
return <CheckCircleIcon className={`${iconClass} text-green-500`} />;
case "error":
return <XCircleIcon className={`${iconClass} text-red-500`} />;
case "warning":
return (
<ExclamationTriangleIcon className={`${iconClass} text-yellow-500`} />
);
case "info":
default:
return (
<InformationCircleIcon className={`${iconClass} text-blue-500`} />
);
}
};
if (!isVisible) return null;
return (
<div
className={`${getAlertStyles()} ${className} ${
isVisible ? "opacity-100 translate-y-0" : "opacity-0 -translate-y-2"
}`}
role="alert"
aria-live="polite"
>
{getIcon()}
<div className="ml-3 flex-1">
{title && <h3 className="text-sm font-semibold mb-1">{title}</h3>}
<div className="text-sm">
{typeof message === "string" ? <p>{message}</p> : message}
</div>
{actions && <div className="mt-3">{actions}</div>}
</div>
{dismissible && (
<button
onClick={handleClose}
className="ml-3 flex-shrink-0 p-1 rounded-md hover:bg-black hover:bg-opacity-10 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors duration-200"
aria-label="Close alert"
>
<XMarkIcon className="w-4 h-4" />
</button>
)}
</div>
);
};
export default Alert;

Usage Example

import React, { useState } from "react";
import Alert from "./Alert";
const App = () => {
const [showAlert, setShowAlert] = useState(false);
return (
<div className="max-w-2xl mx-auto p-6 space-y-6">
<h1 className="text-2xl font-bold text-gray-900">Alert Demo</h1>
<button
onClick={() => setShowAlert(true)}
className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
>
Show Alert
</button>
{showAlert && (
<Alert
type="success"
title="Success!"
message="Your operation was completed successfully."
duration={3000}
onClose={() => setShowAlert(false)}
/>
)}
{/* Different Alert Types */}
<div className="space-y-4">
<Alert type="success" message="Operation completed successfully!" />
<Alert type="error" message="Something went wrong. Please try again." />
<Alert
type="warning"
message="Please review your settings before continuing."
/>
<Alert
type="info"
message="New features are available in your dashboard."
/>
</div>
</div>
);
};
export default App;

Props

PropTypeDefaultDescription
type'success' | 'error' | 'warning' | 'info''info'Alert type affecting color and icon
titlestringundefinedOptional title for the alert
messagestring | ReactNoderequiredMain alert content
durationnumber0Auto-dismiss time in ms (0 = no auto-dismiss)
dismissiblebooleantrueWhether alert can be manually closed
onClosefunctionundefinedCallback when alert is closed
classNamestring''Additional CSS classes
actionsReactNodeundefinedAction buttons or links

Features

  • Four Alert Types: Success, error, warning, info with distinct styling
  • Auto-dismiss: Configurable automatic dismissal
  • Manual Close: User-controlled dismissal with close button
  • Smooth Animations: CSS transitions for show/hide effects
  • Accessibility: ARIA attributes and keyboard navigation
  • Customizable: Easy styling with Tailwind classes
  • Action Support: Add buttons or links for user interaction

Alert Types

  • Success: Green theme with checkmark icon - for confirmations and successful operations
  • Error: Red theme with X icon - for failures and critical issues
  • Warning: Yellow theme with triangle icon - for cautions and important notices
  • Info: Blue theme with info icon - for general information and tips

Installation

Terminal window
npm install @heroicons/react

Example with Actions

<Alert
type="error"
title="Payment Failed"
message="Your payment could not be processed."
actions={
<div className="flex gap-2 mt-2">
<button className="px-3 py-1 bg-red-600 text-white text-sm rounded hover:bg-red-700">
Retry
</button>
<button className="px-3 py-1 bg-gray-200 text-gray-800 text-sm rounded hover:bg-gray-300">
Cancel
</button>
</div>
}
/>

Customization

// Custom styling
<Alert
type="success"
message="Custom styled alert"
className="rounded-xl border-2 p-6"
/>
// No dismiss button
<Alert
type="info"
message="Persistent notification"
dismissible={false}
/>
// Auto-dismiss after 5 seconds
<Alert
type="warning"
message="This will disappear automatically"
duration={5000}
/>