Now.js 980 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import React, { Component } from 'react';
  2. import PropTypes from 'prop-types';
  3. import * as moment from 'moment';
  4. /**
  5. * Updates every second the content of the element
  6. * with the current time formmated
  7. */
  8. export default class Now extends Component {
  9. static propTypes = {
  10. /** string to format current date */
  11. format: PropTypes.string.isRequired
  12. }
  13. state = {
  14. currentTime: null,
  15. format: ''
  16. }
  17. componentDidMount() {
  18. this.updateTime();
  19. this.interval = setInterval(this.updateTime, 1000);
  20. }
  21. componentWillUnmount() {
  22. if(this.interval)
  23. clearInterval(this.interval);
  24. }
  25. updateTime = () => {
  26. this.setState({
  27. currentTime: moment(new Date()).format(this.props.format)
  28. })
  29. }
  30. render() {
  31. return (
  32. <div {...this.props} style={{display: 'inline-block'}}>
  33. {this.state.currentTime}
  34. </div>
  35. )
  36. }
  37. }