React JS - Live clock update
The official React Docs describe exactly what you need (and even explains why you should do it as described):
--> React Docs: State and Lifecycle
Example on CodePen:
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
There seems to be a couple problems with your code. First is the closing div in the render function which causes your element to not even render.
Next you might want to take a look at state/props and React general lifecycle methods to get a better idea of program flow. The setInterval should be put in componentDidMount so its not called every time your component renders and creates a lot of timers. It also might help to put hours, minutes, and seconds as state so that way when these change your component re-renders automatically.
I modified your code below and put an example on jsfiddle. It does not print the seconds properly (just like in your getTime method) but hopefully it will give you a better idea of how logic should flow.
https://jsfiddle.net/rpg6t4uc/
var CityRow = React.createClass({
setTime: function(){
var currentdate = new Date();
var hours = currentdate.getUTCHours() + parseInt(this.props.UTCOffset);
// correct for number over 24, and negatives
if( hours >= 24 ){ hours -= 24; }
if( hours < 0 ){ hours += 12; }
// add leading zero, first convert hours to string
hours = hours + "";
if( hours.length == 1 ){ hours = "0" + hours; }
// minutes are the same on every time zone
var minutes = currentdate.getUTCMinutes();
// add leading zero, first convert hours to string
minutes = minutes + "";
if( minutes.length == 1 ){ minutes = "0" + minutes; }
seconds = currentdate.getUTCSeconds();
console.log(hours, minutes, seconds)
this.setState({
hours: hours,
minutes: minutes,
seconds: seconds
});
},
componentWillMount: function(){
this.setTime();
},
componentDidMount: function(){
window.setInterval(function () {
this.setTime();
}.bind(this), 1000);
},
render: function() {
return(
<div className="city-row" ref="cityRow">
<span className="city-time">{this.state.hours}:{this.state.minutes}:{this.state.seconds}</span>
</div>
)
}
});