Arnaud Rochez Arnaud Rochez - 23 days ago 6
React JSX Question

How do I properly get the date and time?

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;

Answer

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>
    );
  }
});