Last active
February 11, 2020 13:47
-
-
Save JeremyJonas/7a6fef83b60c6ff7f7f5fc4a3027a62c to your computer and use it in GitHub Desktop.
React HOC Timer - provide wrapped component with `time` prop at given interval
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, { PureComponent } from 'react' | |
import PropTypes from 'prop-types' | |
import { omit } from 'lodash' | |
class Timer extends PureComponent { | |
static get propTypes () { | |
return { | |
Component: PropTypes.func.isRequired, | |
interval: PropTypes.number, | |
innerRef: PropTypes.func | |
} | |
} | |
static get defaultProps () { | |
return { | |
interval: 1000 | |
} | |
} | |
state = { | |
tick: 0 | |
} | |
componentWillMount () { | |
this.intervalId = setInterval(this.tick, this.props.interval) | |
} | |
componentWillUnount () { | |
clearInterval(this.intervalId) | |
} | |
tick = () => { | |
this.setState({ | |
tick: this.state.tick + 1 | |
}) | |
} | |
render () { | |
const Component = this.props.Component | |
const props = omit(this.props, Object.keys(Timer.propTypes)) | |
return <Component time={Date.now()} ref={this.props.innerRef} {...props} /> | |
} | |
} | |
export default (Component) => (props) => <Timer Component={Component} {...props} /> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment