Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I properly get the date and time?

Tags:

date

reactjs

I am new to react and trying to get the actual date and time but I can't figure out how to do so :(

Could someone help me please !

I try to get the date in the initial state and actualise it every second. When I run it, I get a white screen.

import React from 'react';
import './Menubar.css';
import Time from 'react-time';

const Menubar = React.createClass({
getInitialState() {
    return {
        now: new Date().now(),
    };
},

getRealTime: function() {
    this.setState(
        {
            now: new Date().now(),
        })
},

/**
 * Render the Menubar component
 * @return {Component} the App Component rendered
 */
render() {
    setInterval(this.getRealTime(), 1000);
    return (
        <div className="Menubar">
            <ul className="Menubar-menu">
                <div className="">
                    <li className="Menubar-name">login name</li>
                    <li className="Menubar-date"><Time value={this.state.now} format="DD/MM/YYYY" /></li>
                    <li className="Menubar-time"><Time value={this.state.now} format="HH:mm:ss" /></li>
                </div>
            </ul>
        </div>
    );
}
});

export default Menubar;
like image 912
Arnaud Rochez Avatar asked Mar 11 '23 16:03

Arnaud Rochez


1 Answers

Two things:

  1. new Date().now() is not a function, new Date() returns the current date and time, so no need to add it.
  2. You try to set the state inside the render function (calling getRealTime every single render, which causes a re-render). As I understand, you want to update the time every second. You could set that up in componentDidMount.

Here's your Menubar component with those things fixed. I also clear the interval when the component unmounts:

const Menubar = React.createClass({
  getInitialState() {
    return {
      now: new Date(),
    };
    this.interval = null;
  },

  componentDidMount: function() {
    const self = this;
    self.interval = setInterval(function() {
      self.setState({
        now: new Date(),
      });
    }, 1000);
  },

  componentWillUnmount: function() {
    clearInterval(this.interval);
  },

  render() {
    return (
      <div className="Menubar">
        <ul className="Menubar-menu">
          <div className="">
            <li className="Menubar-name">login name</li>
            <li className="Menubar-date"><Time value={this.state.now} format="DD/MM/YYYY" /></li>
            <li className="Menubar-time"><Time value={this.state.now} format="HH:mm:ss" /></li>
          </div>
        </ul>
      </div>
    );
  }
});
like image 50
Fabian Schultz Avatar answered Mar 19 '23 09:03

Fabian Schultz