Search code examples
reactjsmomentjsreal-time

ReactJS Time between dates in real time


I'm trying to figure out how I can make a real-time counter that will increment the seconds without having to refresh my page. Here is my code below. I'm quite new to using ReactJS any hints/help will be greatly appreciated. Thanks..

import './Home.css';
import React, { Component } from 'react';
import Moment from 'react-moment';

export default class Home extends Component {
    render() {
        var date = new Date();
        const together = "2017-05-14T06:30";


        return (
            <div>
                <p><Moment interval={1000} diff={together} unit="seconds">{date}</Moment> Seconds</p>
                <p><Moment diff={together} unit="minutes">{date}</Moment> Minutes</p>
                <p><Moment diff={together} unit="days">{date}</Moment> Days</p>
                <p><Moment diff={together} unit="months">{date}</Moment> Months</p>
                <p><Moment diff={together} unit="years" decimal>{date}</Moment> Years</p>
            </div>
        );
    }
}

Solution

  • There's an example of this in the official React docs https://reactjs.org/docs/rendering-elements.html#updating-the-rendered-element

    But the gist of it is you need to use setInterval to update the state of the component. That will cause the component to re-render without a page refresh.

    In your case, you would want to save date to the state's component (e.g. in the constructor) and then read it from the state in render. Then use setInterval to update the state every second.

    import './Home.css';
    import React, { Component } from 'react';
    import Moment from 'react-moment';
    
    export default class Home extends Component {
        constructor() {
             this.state.date = new Date();
        }
        updateTime(){
            var date = this.state.date
            this.setState({date: date.setSeconds(date.getSeconds() + 1);
        }
        componentDidMount(){
            setInterval(this.updateTime, 1000);
        }
        render() {
            const together = "2017-05-14T06:30";
    
    
            return (
                <div>
                    <p><Moment interval={1000} diff={together} unit="seconds">{this.state.date}</Moment> Seconds</p>
                     // etc.  Everywhere you had date becomes this.state.date
                </div>
            );
        }
    }