Created
April 11, 2017 21:26
-
-
Save Magellol/458f13ea1a7d48a1cd7fd8e9e3fc462a to your computer and use it in GitHub Desktop.
Higher-Order component rendering a component after a timeout.
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, { Component, PropTypes } from 'react'; | |
import ReactDOM from 'react-dom'; | |
import Loading from 'loading'; | |
export default function TimedOut(WrappedComponent) { | |
const propTypes = { | |
delay: PropTypes.number.isRequired, | |
}; | |
class Wrapper extends Component { | |
constructor() { | |
super(); | |
this.state = { isTimeOver: false }; | |
} | |
componentDidMount() { | |
this.timeout = setTimeout(() => { | |
this.setState({ isTimeOver: true }); | |
}, this.props.delay); | |
} | |
componentWillUnmount() { | |
clearTimeout(this.timeout); | |
} | |
render() { | |
if (this.state.isTimeOver) { | |
const { delay, ...props } = this.props; // eslint-disable-line | |
return <WrappedComponent {...props} />; | |
} | |
return null; | |
} | |
} | |
Wrapper.displayName = `TimedOut(${WrappedComponent.name})`; | |
Wrapper.propTypes = propTypes; | |
return Wrapper; | |
} | |
const DelayedLoading = TimedOut(Loading); | |
ReactDOM.render( | |
<DelayedLoading delay={1000} /> | |
document.getElementById('root'), | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment