Skip to content

ModernAlert (components/ui/modern-alert.tsx)

Overview

A modern alert component that displays animated notification messages with typing effect and automatic dismissal.

Features

  • Animated entrance and exit transitions
  • Typing effect for text display
  • Automatic dismissal after 5 seconds
  • Dark mode support
  • Responsive design
  • Custom text support
  • Motion animations
  • Info icon with pulse effect

Dependencies

import React, { useState, useEffect } from 'react'
import { motion, AnimatePresence } from 'framer-motion'

Props

interface ModernAlertProps {
  text?: string;  // Default: "This is a sample alert notification!"
}

Implementation

State Management

const [isVisible, setIsVisible] = useState(true)
const [typedText, setTypedText] = useState("")

Methods

// Typing effect implementation
const typeText = (index: number) => {
  if (index <= text.length) {
    setTypedText(text.slice(0, index))
    typingTimer = setTimeout(() => typeText(index + 1), 30)
  }
}

// Cleanup timers
useEffect(() => {
  let typingTimer: NodeJS.Timeout
  let hideTimer: NodeJS.Timeout

  typeText(0)
  hideTimer = setTimeout(() => setIsVisible(false), 5000)

  return () => {
    clearTimeout(typingTimer)
    clearTimeout(hideTimer)
  }
}, [text])

Unique Functionality

  • Typing animation effect for text
  • Automatic dismissal after 5 seconds
  • Spring-based entrance/exit animations
  • Pulsing info icon animation

HTML Structure

<AnimatePresence>
  {isVisible && (
    <motion.div
      initial={{ x: '100%', opacity: 0 }}
      animate={{ x: 0, opacity: 1 }}
      exit={{ x: '100%', opacity: 0 }}
      transition={{ type: 'spring', stiffness: 100, damping: 20 }}
      className="fixed top-4 right-4 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 p-4 rounded-lg shadow-lg max-w-sm z-50 border border-gray-200 dark:border-gray-700"
    >
      <div className="flex items-center space-x-3">
        <div className="flex-shrink-0">
          <motion.svg {...iconProps} />
        </div>
        <div className="flex-1 min-w-0">
          <p className="text-sm font-bold">{typedText}</p>
        </div>
      </div>
    </motion.div>
  )}
</AnimatePresence>

API Integration

No direct API integration required.

Components Used

  • AnimatePresence from framer-motion
  • motion.div from framer-motion
  • motion.svg from framer-motion

Notes

  • Ensure proper cleanup of timers on component unmount
  • Consider accessibility implications of animations
  • Text typing speed can be adjusted via the timeout value
  • Alert position is fixed to top-right corner
  • Uses Tailwind CSS for styling