Last active
August 30, 2018 17:16
-
-
Save tomfordweb/1f7cef5f1eaaf47ed266daba2e9fb234 to your computer and use it in GitHub Desktop.
React - Hide Component after X seconds
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 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: 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; | |
}.bind(this), this.props.delay); | |
} | |
render() { | |
return this.state.visible | |
? <div>{this.props.children}</div> | |
: <span />; | |
} | |
} | |
// Usage | |
// <Expire delay={2000}><p>Content To Hide after 2 seconds</Expire> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment