delayed-show.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import React from 'react';
  2. export default class DelayedShow extends React.Component {
  3. constructor(props, context) {
  4. super(props, context);
  5. this.state = {
  6. show: false
  7. };
  8. }
  9. componentWillMount() {
  10. if (this.props.show) {
  11. this.scheduleShow();
  12. }
  13. }
  14. componentWillUnmount() {
  15. this.cancelShow();
  16. }
  17. componentWillReceiveProps(nextProps) {
  18. if (nextProps.show === this.props.show) {
  19. return;
  20. }
  21. if (nextProps.show) {
  22. this.scheduleShow();
  23. } else {
  24. this.cancelShow();
  25. this.setState({ show: false });
  26. }
  27. }
  28. scheduleShow() {
  29. this.showTimeout = setTimeout(() => this.setState({ show: true }), this.props.delay);
  30. }
  31. cancelShow() {
  32. clearTimeout(this.showTimeout);
  33. }
  34. render() {
  35. const { children } = this.props;
  36. const { show } = this.state;
  37. const style = {
  38. opacity: show ? 1 : 0,
  39. transition: 'opacity 0.5s ease-in-out',
  40. };
  41. return (
  42. <div style={style}>
  43. {children}
  44. </div>
  45. );
  46. }
  47. }
  48. DelayedShow.defaultProps = {
  49. delay: 1000
  50. };