import React, { useState, useCallback, useRef } from 'react'; import { useSpring, animated } from 'react-spring'; import { Wrapper, Content, Message, Description, AlertIcon, CloseButton, CloseIcon } from './style'; import { IAlert } from './types'; function useHeight(): [(node: any) => void, number] { const [height, setHeight] = useState(0); const measuredRef = useCallback(node => { if (node !== null) { setHeight(node.getBoundingClientRect().height); } }, []); return [measuredRef, height]; } export const Alert: React.FC = ({ type = 'info', message, closable = false, closeText, description, showIcon = false, icon, onClose, afterClose, children, }) => { const parentRef = useRef(null); const [v, setV] = useState(true); const [measuredRef, viewHeight] = useHeight(); const handleClose = useCallback((e: any) => { setV(false); onClose && onClose(e); }, []); const { height, opacity } = useSpring({ opacity: v ? 1 : 0, height: v ? viewHeight : 0, config: { clamp: true }, onRest: (e: any) => { if (!v && !e.height) { afterClose && afterClose(); parentRef.current.parentNode.removeChild(parentRef.current); } }, }); return ( {showIcon ? icon ? icon : : null} {children ? ( children ) : ( <> {message} {description} )} {closable ? ( {closeText ? closeText : } ) : null} ); }; Alert.defaultProps = {}; export default Alert;