Skip to content

Instantly share code, notes, and snippets.

@afrodesia
Last active December 27, 2016 22:02
Show Gist options
  • Select an option

  • Save afrodesia/cc1ebd16fe80fbc31d2d07566121a449 to your computer and use it in GitHub Desktop.

Select an option

Save afrodesia/cc1ebd16fe80fbc31d2d07566121a449 to your computer and use it in GitHub Desktop.
Clock code that can be used in React.js
import React from 'react'
class Clock extends React.Component {
constructor(props){
super(props)
this.state = this.getTime()
}
componentDidMount() {
this.setTimer()
}
setTimer(){
this.timeout = setTimeout(this.updateClock.bind(this), 1000)
}
updateClock(){
this.setState(this.getTime, this.setTimer)
}
getTime(){
const currentTime = new Date()
return {
hours : currentTime.getHours(),
minutes : currentTime.getMinutes(),
seconds : currentTime.getSeconds(),
ampm : currentTime.getHours() >= 12 ? 'pm' : 'am'
}
}
render(){
const {hours,minutes,seconds, ampm} = this.state
return(
<section className="clock">
<h2>
<span className="hours">
{ hours === 0 ? 12 : (hours > 12) ? hours - 12 : hours }
</span>:
<span className="minutes">
{ minutes > 9 ? minutes : `0${minutes}` }
</span>
<span className="seconds">
({ seconds > 9 ? seconds : `0${seconds}`})
</span>
<span className="timeofday">{ampm}</span>
</h2>
</section>
)
}
}
export default Clock
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment