Last active
December 27, 2016 22:02
-
-
Save afrodesia/cc1ebd16fe80fbc31d2d07566121a449 to your computer and use it in GitHub Desktop.
Clock code that can be used in React.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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