From e29d6c3fcecffed7844051b2bef9b345e71249ad Mon Sep 17 00:00:00 2001 From: edumoreira1506 Date: Fri, 8 Nov 2019 16:17:44 -0300 Subject: [PATCH] Refactor with hooks --- src/Notification.js | 93 +++++++++++++++++++-------------------------- 1 file changed, 39 insertions(+), 54 deletions(-) diff --git a/src/Notification.js b/src/Notification.js index 16e21ae..6b628c0 100644 --- a/src/Notification.js +++ b/src/Notification.js @@ -1,70 +1,55 @@ -import React from 'react'; +import React, { useEffect } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; -class Notification extends React.Component { - static propTypes = { - type: PropTypes.oneOf(['info', 'success', 'warning', 'error']), - title: PropTypes.node, - message: PropTypes.node.isRequired, - timeOut: PropTypes.number, - onClick: PropTypes.func, - onRequestHide: PropTypes.func - }; - - static defaultProps = { - type: 'info', - title: null, - message: null, - timeOut: 5000, - onClick: () => { - }, - onRequestHide: () => { - } - }; - - componentDidMount = () => { - const { timeOut } = this.props; +const Notification = ({ + type = 'info', + title = null, + message = null, + timeOut = 5000, + onClick = () => { }, + onRequestHide = () => { } +}) => { + let timer; + + useEffect(() => { if (timeOut !== 0) { - this.timer = setTimeout(this.requestHide, timeOut); + timer = setTimeout(requestHide, timeOut); } - }; - componentWillUnmount = () => { - if (this.timer) { - clearTimeout(this.timer); + if (timer) { + clearTimeout(timer); } - }; + }); - handleClick = () => { - const { onClick } = this.props; - if (onClick) { - onClick(); - } - this.requestHide(); + const handleClick = () => { + if (onClick) onClick(); + requestHide(); }; - requestHide = () => { - const { onRequestHide } = this.props; - if (onRequestHide) { - onRequestHide(); - } + const requestHide = () => { + if (onRequestHide) onRequestHide(); }; - render() { - const { type, message } = this.props; - let { title } = this.props; - const className = classnames(['notification', `notification-${type}`]); - title = title ? (

{title}

) : null; - return ( -
-
- {title} -
{message}
-
+ const className = classnames(['notification', `notification-${type}`]); + title = title ? (

{title}

) : null; + return ( +
+
+ {title} +
{message}
- ); - } +
+ ); +} + +Notification.propTypes = { + type: PropTypes.oneOf(['info', 'success', 'warning', 'error']), + title: PropTypes.node, + message: PropTypes.node.isRequired, + timeOut: PropTypes.number, + onClick: PropTypes.func, + onRequestHide: PropTypes.func } export default Notification;