Created
November 17, 2020 13:06
-
-
Save debanshu/555d2bf0fdb330c540946fa4ce1428ff to your computer and use it in GitHub Desktop.
Small App with Timer code
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, { Component, useState } from "react"; | |
| import "../styles/App.css"; | |
| class App extends Component { | |
| constructor(props) { | |
| super(props); | |
| this.state = { | |
| time: new Date(), | |
| }; | |
| this.intervalId = null; | |
| } | |
| render() { | |
| return ( | |
| <div className="Clock"> | |
| <h3 id="time">{this.getTimeString()}</h3> | |
| </div> | |
| ); | |
| } | |
| componentDidMount() { | |
| this.intervalId = setInterval(() => { | |
| this.setState({ | |
| time: new Date() | |
| }) | |
| }, 1*1000); | |
| } | |
| componentWillUnmount() { | |
| clearInterval(this.intervalId); | |
| } | |
| getTimeString() { | |
| const currTime = this.state.time; | |
| const [hours, minutes, seconds] = [ | |
| currTime.getHours(), | |
| currTime.getMinutes(), | |
| currTime.getSeconds(), | |
| ]; | |
| const amOrPm = hours >= 12 ? "PM" : "AM"; | |
| const twelveHourFormat = hours > 12 ? hours - 12 : hours; | |
| const hourString = this.padNumberToTwoDigits(twelveHourFormat); | |
| const minuteString = this.padNumberToTwoDigits(minutes); | |
| const secondString = this.padNumberToTwoDigits(seconds); | |
| const timeString = `${hourString}:${minuteString}:${secondString} ${amOrPm}`; | |
| // hourString + ":" + minuteString + ":" + secondString + " " + amOrPm | |
| return timeString; | |
| } | |
| padNumberToTwoDigits(num) { | |
| return `${num < 10 ? "0" : ""}${num}`; | |
| } | |
| } | |
| export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment