Created
December 11, 2018 19:43
-
-
Save mminer/e0b9a8a45a879ad963b15b28d3804806 to your computer and use it in GitHub Desktop.
React component that displays an auto-updating relative time.
This file contains 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 moment from 'moment'; | |
import PropTypes from 'prop-types'; | |
import { Component, createElement as h } from 'react'; | |
class RelativeTime extends Component { | |
constructor(props) { | |
super(props); | |
this.intervalId = null; | |
this.state = { output: moment(props.time).fromNow() }; | |
this.updateOutput = this.updateOutput.bind(this); | |
} | |
componentDidMount() { | |
this.intervalId = window.setInterval( | |
this.updateOutput, | |
this.props.intervalDelay | |
); | |
} | |
componentWillUnmount() { | |
window.clearInterval(this.intervalId); | |
} | |
render() { | |
return h('time', { dateTime: this.props.time }, this.state.output); | |
} | |
updateOutput() { | |
this.setState({ output: moment(this.props.time).fromNow() }); | |
} | |
} | |
RelativeTime.defaultProps = { | |
intervalDelay: 10000, // 10 seconds | |
}; | |
RelativeTime.propTypes = { | |
intervalDelay: PropTypes.number, | |
time: PropTypes.oneOfType([ | |
PropTypes.instanceOf(Date), | |
PropTypes.string, | |
]).isRequired, | |
}; | |
export default RelativeTime; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment