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;
Two things:
new Date().now()
is not a function, new Date()
returns the current date and time, so no need to add it.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>
);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With