import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { Transition } from '@headlessui/react';
import { ExclamationIcon, CheckCircleIcon } from '@heroicons/react/outline';
/**
* Alert component to display messages with different types (success or error).
*
* This component renders an alert message with either a success or error icon
* and corresponding styling based on the provided type prop. The alert is
* automatically dismissed after 5 seconds.
*
* @component
* @param {Object} props - The properties passed to the component.
* @param {string} props.message - The message to be displayed in the alert.
* @param {'success' | 'error'} props.type - The type of alert (success or error).
* @returns {JSX.Element} The JSX element representing the Alert component.
* @example
* // Example usage of Alert component
* <Alert message="Action was successful!" type="success" />
* @example
* // Another example usage of Alert component
* <Alert message="An error occurred!" type="error" />
*/
const Alert = ({ message, type }) => {
const [showAlert, setShowAlert] = useState(false);
useEffect(() => {
if (message) {
setShowAlert(true);
const timer = setTimeout(() => {
setShowAlert(false);
}, 5000);
return () => clearTimeout(timer);
}
}, [message]);
if (!showAlert) return null;
return (
<Transition
show={true}
as="div"
enter="transition-opacity duration-300"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="transition-opacity duration-300"
leaveFrom="opacity-100"
leaveTo="opacity-0"
className={`bg-${type === 'error' ? 'red' : 'green'}-100 border-${type === 'error' ? 'red' : 'green'}-400 text-${type === 'error' ? 'red' : 'green'}-700 px-4 py-3 rounded relative`}
role="alert"
>
<div className="flex items-center">
<div className="flex-shrink-0">
{type === 'error' ? (
<ExclamationIcon className="h-5 w-5 text-red-400" />
) : (
<CheckCircleIcon className="h-5 w-5 text-green-400" />
)}
</div>
<div className="ml-3">
<p className="text-sm font-medium">
{type === 'error' ? 'Error' : 'Success'}
</p>
<p className="text-sm">{message}</p>
</div>
</div>
</Transition>
);
};
/**
* PropTypes for Alert component.
*
* Ensures that the props passed to the Alert component are of the correct type.
*
* @static
* @property {string} message - The message to be displayed in the alert.
* @property {'success' | 'error'} type - The type of alert (success or error).
*/
Alert.propTypes = {
message: PropTypes.string.isRequired,
type: PropTypes.oneOf(['success', 'error']).isRequired,
};
export default Alert;