Skip to content

Instantly share code, notes, and snippets.

@andersonbosa
Created October 30, 2023 18:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andersonbosa/78fb824aac17566689901c605c606d70 to your computer and use it in GitHub Desktop.
Save andersonbosa/78fb824aac17566689901c605c606d70 to your computer and use it in GitHub Desktop.
Use React to implement a Popup Queu to notifications, alerts, errors, etc
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