Last active
March 21, 2017 21:18
-
-
Save ericchernuka/683bd1deaed932173ad2fa86a90b2f54 to your computer and use it in GitHub Desktop.
React Interval Component
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 } from 'react'; | |
/** | |
* Declarative approach to setInterval | |
*/ | |
class ReactInterval extends Component { | |
static propTypes = { | |
enabled: React.PropTypes.bool, | |
interval: React.PropTypes.number, // interval time in ms | |
onInterval: React.PropTypes.func.isRequired | |
} | |
static defaultProps = { | |
enabled: false, | |
interval: 1000 | |
} | |
componentDidMount() { | |
if (this.props.enabled) { | |
this.start() | |
} | |
} | |
componentDidUpdate(prevProps) { | |
if (this.props.enabled !== prevProps.enabled) { | |
if (this.props.enabled) { | |
this.start() | |
} else { | |
clearInterval(this.interval) | |
} | |
} | |
} | |
componentWillUnmount() { | |
clearInterval(this.interval) | |
} | |
start = () => { | |
this.interval = setInterval(this.tick, this.props.interval) | |
} | |
tick = () => { | |
this.props.onInterval && this.props.onInterval() | |
} | |
render() { | |
return this.props.children || null | |
} | |
} | |
export default ReactInterval |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment