Removing element from DOM after set amount of time
One way is to create an Expire component which will hide its children after a delay. You can use this in conjunction with a CSSTransitionGroup to do the fade out behavior.
jsbin
Usage:
render: function(){
return <Expire delay={5000}>This is an alert</Expire>
}
The component:
var Expire = React.createClass({
getDefaultProps: function() {
return {delay: 1000};
},
getInitialState: function(){
return {visible: true};
},
componentWillReceiveProps: function(nextProps) {
// reset the timer if children are changed
if (nextProps.children !== this.props.children) {
this.setTimer();
this.setState({visible: true});
}
},
componentDidMount: function() {
this.setTimer();
},
setTimer: function() {
// clear any existing timer
this._timer != null ? clearTimeout(this._timer) : null;
// hide after `delay` milliseconds
this._timer = setTimeout(function(){
this.setState({visible: false});
this._timer = null;
}.bind(this), this.props.delay);
},
componentWillUnmount: function() {
clearTimeout(this._timer);
},
render: function() {
return this.state.visible
? <div>{this.props.children}</div>
: <span />;
}
});
Furthermore simplified way using Hooks.
From React Hooks docs,
useEffect
hook combinely does all these threecomponentDidMount
,componentDidUpdate
, andcomponentWillUnmount
Your Expire
component should be
import React, { useEffect, useState } from "react";
const Expire = props => {
const [visible, setVisible] = useState(true);
useEffect(() => {
const timer = setTimeout(() => {
setVisible(false);
}, props.delay);
return () => clearTimeout(timer)
}, [props.delay]);
return visible ? <div>{props.children}</div> : <div />;
};
export default Expire;
Now, pass the delay
prop in Expire
component.
<Expire delay="5000">Hooks are awesome!</Expire>
I created a working example using Codesandbox