Skip to content

Commit

Permalink
Refactor clock display logic into its own component
Browse files Browse the repository at this point in the history
  • Loading branch information
rocketkai committed Jun 11, 2022
1 parent 6c7c6c8 commit 833a716
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 23 deletions.
25 changes: 2 additions & 23 deletions src/App.js
@@ -1,36 +1,15 @@
import React from "react";
import logo from "./logo.png";
import "./App.css";
import Clock from "./Clock.js";

class App 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 (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
{/* Render date value that is stored in state */}
<p>{this.state.date.toString()}</p>
<Clock />
</header>
</div>
);
Expand Down
33 changes: 33 additions & 0 deletions src/Clock.js
@@ -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;

0 comments on commit 833a716

Please sign in to comment.