Created
April 21, 2019 11:32
-
-
Save craicoverflow/b2e840f409e783b88dda50a6fb1cf6d0 to your computer and use it in GitHub Desktop.
React Alert component using hooks
This file contains hidden or 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 React, { useState, useEffect } from "react"; | |
import PropTypes from "prop-types"; | |
/** | |
* Customisable alert component that remains hidden until called. | |
* | |
* @param {boolean} props.visible - The current visibility of the component. | |
* @param {number} [props.duration] - The time in milliseconds to display the component for. If not set, the component will stay open. | |
* @param {func} onTimeoutEnd - Set visible state of component from parent. | |
* @param {*} props.children - Child components. | |
*/ | |
export const Alert = ({ visible, duration, onTimeoutEnd, children }) => { | |
const [isVisible, setVisibility] = useState(null); | |
useEffect(() => { | |
setVisibility(visible); | |
}, [visible]); | |
if (!isVisible) return null; | |
if (duration) { | |
setTimeout(() => { | |
setVisibility(false); | |
onTimeoutEnd(false); | |
}, duration); | |
} | |
return children; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment