Skip to content

Instantly share code, notes, and snippets.

@tomfordweb
Created October 31, 2018 18:50
Show Gist options
  • Save tomfordweb/dbd874b666d71527ab66ec40a880d249 to your computer and use it in GitHub Desktop.
Save tomfordweb/dbd874b666d71527ab66ec40a880d249 to your computer and use it in GitHub Desktop.
React - Hide content after a timer
'use strict';
import React from 'react';
import update from 'immutability-helper';
export default class Expire extends React.Component {
constructor(props) {
super(props);
this.state = {
delay: props.delay || 1000,
visible: true
}
this.setTimer = this.setTimer.bind(this);
}
componentWillReceiveProps(nextProps) {
if (nextProps.children !== this.props.children) {
this.setTimer();
this.setState(update(this.state, {
visible: {$set: true }
}))
}
}
componentDidMount() { this.setTimer(); }
componentWillUnmount() { clearTimeout(this._timer); }
setTimer() {
// 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;
if(this.props.callback) {
this.props.callback();
}
}.bind(this), this.props.delay);
}
render() {
return this.state.visible
? <div>{this.props.children}</div>
: <span />;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment