Reputation: 61
I just started learning react recently. I want a tick timer to show up on the screen and the time will update every one second.
Now the time shows up when the page is initially loaded, but it is static. There is no error in console. What should I do in my code?
Here is a part of my code:
function timer(){
return new Date().toLocaleTimeString()
}
setInterval(timer, 1000);
const element = (
<div>
{getGreeting(user)}
<h1>It is {timer()}.</h1>
</div>
);
ReactDOM.render(
element,
document.getElementById('container')
);
And here is a screenshot of result: enter image description here
Thanks!!
Upvotes: 2
Views: 9495
Reputation: 180
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(props){
super(props);
this.state = {
timer:""
}
}
componentWillMount(){
setTimeout(()=>{
this.setState({
timer: new Date().toLocaleTimeString()
})
this.componentWillMount();
})
}
render() {
return (
<div className="App">
<h1>Timer</h1>
<h1>{this.state.timer}</h1>
</div>
);
}
}
export default App;
Upvotes: -1
Reputation: 94309
The current display time would be a state of your component. Use setInterval
to update the state to trigger a re-rendering.
Better yet, use setTimeout
and set the duration to the next second minus the current time.
Here's an example: https://jsfiddle.net/DerekL/3yLneqy7/
class Time extends React.Component {
constructor(props){
super(props);
this.timer = 0;
this.state = {
time: new Date()
};
}
componentWillMount(){
// set up timer
this.timer = setTimeout(() => {
this.setState({
time: new Date()
});
this.componentWillMount();
}, Math.floor(Date.now() / 1000) * 1000 + 1000 - Date.now());
}
componentWillUnmount(){
// remove timer
clearTimeout(this.timer);
}
render() {
// render the current time
return this.state.time.toLocaleTimeString();
}
}
class App extends React.Component {
render() {
return (
<span>
<span>The time is </span>
<Time/>.
</span>
);
}
}
ReactDOM.render(<App />, document.body);
<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
By seeing how you are doing
function timer(){
return new Date().toLocaleTimeString()
}
setInterval(timer, 1000);
I believe you are new to JavaScript. I suggest you to code without using any library or framework (with vanilla Javascript) until you are confident with the basics.
Upvotes: 3