Skip to content

Instantly share code, notes, and snippets.

@mminer
Created December 11, 2018 19:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mminer/e0b9a8a45a879ad963b15b28d3804806 to your computer and use it in GitHub Desktop.
Save mminer/e0b9a8a45a879ad963b15b28d3804806 to your computer and use it in GitHub Desktop.
React component that displays an auto-updating relative time.
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