generated from rocketacademy/cra-bootcamp-template
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Refactor clock display logic into its own component
- Loading branch information
Showing
2 changed files
with
35 additions
and
23 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
import React from "react"; | ||
|
||
class Clock extends React.Component { | ||
constructor(props) { | ||
super(props); | ||
// Initialise component state to contain "date" attribute with current date and time | ||
this.state = { date: new Date() }; | ||
} | ||
|
||
componentDidMount() { | ||
// Set date value in state every second to current date and time | ||
// Save setInterval timer ID in class variable for teardown in another class method | ||
this.timerId = setInterval(() => { | ||
this.setState({ | ||
date: new Date(), | ||
}); | ||
}, 1000); | ||
} | ||
|
||
componentWillUnmount() { | ||
// Teardown setInterval timer with timer ID saved as class variable | ||
clearInterval(this.timerId); | ||
} | ||
|
||
render() { | ||
return ( | ||
// Render date value that is stored in state | ||
<p>{this.state.date.toString()}</p> | ||
); | ||
} | ||
} | ||
|
||
export default Clock; |