Created
October 30, 2023 18:25
-
-
Save andersonbosa/78fb824aac17566689901c605c606d70 to your computer and use it in GitHub Desktop.
Use React to implement a Popup Queu to notifications, alerts, errors, etc
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component } from 'react' | |
import styles from './Popup.module.css' | |
interface PopupProps { | |
type: 'alert' | 'notification' | 'error' | |
title: string | |
body: string | |
visibilityDuration?: number | |
} | |
interface PopupState { | |
isVisible: boolean | |
} | |
class Popup extends Component<PopupProps, PopupState> { | |
visibilityTimer: NodeJS.Timeout | null = null; | |
constructor(props: PopupProps) { | |
super(props) | |
this.state = { | |
isVisible: true, | |
} | |
} | |
componentDidMount () { | |
const { visibilityDuration } = this.props | |
if (visibilityDuration && visibilityDuration > 0) { | |
this.visibilityTimer = setTimeout(this.hidePopup, visibilityDuration) | |
} | |
} | |
componentWillUnmount () { | |
this.clearVisibilityTimer() | |
} | |
clearVisibilityTimer = () => { | |
if (this.visibilityTimer) { | |
clearTimeout(this.visibilityTimer) | |
} | |
}; | |
hidePopup = () => { | |
this.setState({ isVisible: false }, this.clearVisibilityTimer) | |
}; | |
render () { | |
const { type, title, body } = this.props | |
const { isVisible } = this.state | |
return isVisible ? ( | |
<div className={styles.popup}> | |
<div className={`${styles.popupContent} ${styles[type]}`}> | |
<h2>{title}</h2> | |
<p>{body}</p> | |
</div> | |
</div> | |
) : null | |
} | |
} | |
export default Popup |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment