Reputation: 7
The foll. is react docs code. https://codepen.io/gaearon/pen/gwoJZk?editors=0010
I am trying to run clock given by react docs in a local setup, with slight modifications, but the clock is displaying current time, without any increment in secs or mins.
// components/Clock.js
import React from 'react';
function tick() {
const element = (
<div>
<h1>Hello, world!</h1>
<h2>It is {new Date().toLocaleTimeString()}.</h2>
</div>
);
return element;
}
setInterval(tick, 1000);
export default tick;
// src/App.js
import React, { Component } from 'react';
import Clock from './components/Clock';
class App extends Component {
render() {
return (
<div>
<Clock />
</div>
);
}
}
export default App;
why the time is not updating ?
Upvotes: 0
Views: 122
Reputation: 2732
I have created a sample for you. Actually you have to use setInterval and need to store current time into state of the component.
https://stackblitz.com/edit/react-nuhgwi?file=Hello.js
Upvotes: 1
Reputation: 15831
The right way in react would be
const myInterval; // Useful for manage and refer to the setinteval object
updateTime = () => setState({currentTime: new Date().toLocaleTimeString())
startInterval = () => myInterval = setInterval(updateTime, 1000);
In render:
<div>
{this.state.currentTime}
</div>
Upvotes: 0
Reputation: 320
setInterval is not used in your version. You just export tick component. Move setInterval inside tick
Upvotes: 0