Skip to content

Instantly share code, notes, and snippets.

@craicoverflow
Created April 21, 2019 11:32
Show Gist options
  • Save craicoverflow/b2e840f409e783b88dda50a6fb1cf6d0 to your computer and use it in GitHub Desktop.
Save craicoverflow/b2e840f409e783b88dda50a6fb1cf6d0 to your computer and use it in GitHub Desktop.
React Alert component using hooks
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