Created
December 30, 2018 07:41
-
-
Save andreconghau/f340d64d7d18a94dec63cc97ac4bfafd to your computer and use it in GitHub Desktop.
State to set timer
This file contains 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
class Clock extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = this.getTime(); | |
} | |
componentDidMount() { | |
this.setTimer(); | |
} | |
componentWillUnmount() { | |
if (this.timeout) { | |
clearTimeout(this.timeout); | |
} | |
} | |
getTime() { | |
const currentTime = new Date(); | |
return { | |
hours: currentTime.getHours(), | |
minutes: currentTime.getMinutes(), | |
seconds: currentTime.getSeconds(), | |
ampm: currentTime.getHours() >= 12 ? 'pm' : 'am' | |
} | |
} | |
setTimer() { | |
clearTimeout(this.timeout); | |
this.timeout = setTimeout(this.updateClock.bind(this), 1000); | |
} | |
updateClock() { | |
this.setState(this.getTime, this.setTimer); | |
} | |
render() { | |
const {hours, minutes, seconds, ampm} = this.state; | |
return ( | |
<div className="clock"> | |
{ | |
hours == 0 ? 12 : | |
(hours > 12) ? | |
hours - 12 : hours | |
}:{ | |
minutes > 9 ? minutes : `0${minutes}` | |
}:{ | |
seconds > 9 ? seconds : `0${seconds}` | |
} {ampm} | |
</div> | |
) | |
} | |
} | |
var mountClock = document.querySelector('#clock'); | |
ReactDOM.render(<Clock />, mountClock); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment