So you were on the right track. Inside your componentDidMount()
you could have finished the job by implementing setInterval()
to trigger the change, but remember the way to update a components state is via setState()
, so inside your componentDidMount()
you could have done this:
componentDidMount() {
setInterval(() => {
this.setState({time: Date.now()})
}, 1000)
}
Also, you use Date.now()
which works, with the componentDidMount()
implementation I offered above, but you will get a long set of nasty numbers updating that is not human readable, but it is technically the time updating every second in milliseconds since January 1, 1970, but we want to make this time readable to how we humans read time, so in addition to learning and implementing setInterval
you want to learn about new Date()
and toLocaleTimeString()
and you would implement it like so:
class TimeComponent extends Component {
state = { time: new Date().toLocaleTimeString() };
}
componentDidMount() {
setInterval(() => {
this.setState({ time: new Date().toLocaleTimeString() })
}, 1000)
}
Notice I also removed the constructor()
function, you do not necessarily need it, my refactor is 100% equivalent to initializing site with the constructor()
function.