ErrorBoundary.jsx
1 import { Component } from 'react'; 2 import { motion } from 'framer-motion'; 3 4 class ErrorBoundary extends Component { 5 state = { hasError: false, error: null }; 6 7 static getDerivedStateFromError(error) { 8 return { hasError: true, error }; 9 } 10 11 componentDidCatch(error, errorInfo) { 12 console.error('ErrorBoundary caught:', error, errorInfo); 13 } 14 15 render() { 16 if (this.state.hasError) { 17 return ( 18 <motion.div 19 className="bg-red-100 p-6 rounded-xl shadow-lg text-red-600" 20 initial={{ opacity: 0 }} 21 animate={{ opacity: 1 }} 22 transition={{ duration: 0.3 }} 23 > 24 <h2 className="text-xl font-semibold mb-4">Something went wrong</h2> 25 <p>{this.state.error?.message || 'An unexpected error occurred'}</p> 26 <motion.button 27 className="mt-4 bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600" 28 onClick={() => this.setState({ hasError: false, error: null })} 29 whileHover={{ scale: 1.05 }} 30 whileTap={{ scale: 0.95 }} 31 > 32 Try Again 33 </motion.button> 34 </motion.div> 35 ); 36 } 37 38 return this.props.children; 39 } 40 } 41 42 export default ErrorBoundary;