Skip to content

Instantly share code, notes, and snippets.

@aortbals
Last active April 11, 2019 02:21
Show Gist options
  • Save aortbals/48fa1e3526e42698f24dc58c2f03bf74 to your computer and use it in GitHub Desktop.
Save aortbals/48fa1e3526e42698f24dc58c2f03bf74 to your computer and use it in GitHub Desktop.
React <Moment /> Component
import moment from 'moment';
import React, { Component, PropTypes } from 'react';
export default class Moment extends Component {
static propTypes = {
children: PropTypes.func,
date: PropTypes.oneOfType([
PropTypes.string,
PropTypes.instanceOf(Date),
]),
format: PropTypes.string,
liveUpdate: PropTypes.bool.isRequired,
liveUpdateInterval: PropTypes.number,
};
static defaultProps = {
format: 'MMMM Do YYYY, h:mm a',
liveUpdate: false,
};
componentDidMount() {
const { liveUpdate, liveUpdateInterval } = this.props;
if (liveUpdate || liveUpdateInterval) {
const interval = liveUpdateInterval || 10000;
this.interval = setInterval(() => this.forceUpdate(), interval);
}
}
componentWillUnmount() {
if (this.interval) {
clearInterval(this.interval);
}
}
render() {
const { date, children, format, ...rest } = this.props;
return (
<div {...rest}>
{children ?
children(moment(date))
:
moment(date).format(format)
}
</div>
);
}
}

Basic Format API

Since the usage of format is so common, there is an easy API:

<Moment date={publishedAt} format="MMMM D, YYYY" />

Advanced API

For more advanced usage of the Moment API, you can use <Moment /> as a Function as Child component:

<Moment date={updatedAt} liveUpdate>
  {moment => moment.fromNow()}
</Moment>

liveUpdate will re-render the component every 10 seconds for periodic updates. Override the default interval of 10 seconds by providing liveUpdateInterval.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment